为什么我在var " first"上的"private"关键字不起作用?



这些天我在CS61b上工作。我被访问控制的讲座卡住了。变量first和类IntNode上的"private"关键字无法正常工作。

在谷歌上搜索,但一无所获。

public class SLList {
private IntNode first;
/**
* If the nested class never uses any instance variables or methods of the outer
* class, declare it static.
*/
private static class IntNode {
public IntNode next;
public int item;
public IntNode(int i, IntNode n) {
next = n;
item = i;
}
}
public SLList(int x) {
first = new IntNode(x, null);
}

public void addFirst(int x) {
first = new IntNode(x, first);
}
public int getFirst() {
return first.item;
}
/** ----------------SIZE---------------------- */
private int size(IntNode L) {
if (L.next == null) {
return 1;
}
return 1 + size(L.next);
}
public int size() {
return size(first);
}
/**-------------------SIZE------------------- */

/**---------------add LAST ------------------*/
/** how to solve null pointer expectation? */
public void addLast(int x) {
IntNode p=first;
while(p.next!=null){
p=p.next;
}
p.next=new IntNode(x, null);
}
/**---------------add LAST ------------------*/
public static void main(String[] args) {
SLList L = new SLList(5);
L.addFirst(10);
L.addFirst(15);
System.out.println(L.getFirst());
System.out.println(L.size());
L.addLast(20);
L.first.next.next = L.first.next;  /** <----- I can still get√ access to first. */
}
}

我预计会有错误:首先在SLList中有私有类,但我没有做错什么。

参见Java语言规范§6.6.1:

引用类型的成员(类、接口、字段或方法(或类类型的构造函数,只有当该类型是可访问的并且该成员或构造函数被声明为允许访问时,才可以访问:

  • 如果成员或构造函数被声明为公共,则允许访问。

  • 缺少访问修饰符的接口的所有成员都是隐式公共的。

  • 否则,如果成员或构造函数被声明为受保护,则只有当以下情况之一为真时才允许访问:

    • 从包含声明受保护成员或构造函数的类的包中访问成员或构造函数。

    • 访问是正确的,如§6.6.2所述。

  • 否则,如果成员或构造函数是用包访问权声明的,那么只有当访问发生在声明类型的包内时,才允许访问。

    在没有访问修饰符的情况下声明的类成员或构造函数隐式具有包访问权限。

  • 否则,成员或构造函数被声明为私有,并且当且仅当访问发生在包含成员或构造函数声明的顶级类型(§7.6(的主体内时,才允许访问。

(强调矿(

由于您对first的访问属于同一顶级类型,因此您可以访问它而不会出现任何问题、错误或其他任何问题。

最新更新