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

时间:2019-11-03 01:21:33

标签: java data-structures

这些天我正在使用CS61b。而且我陷入了访问控制的讲座。我在变量first和类IntNode上的“ private”关键字无法正常工作。

在Google上进行搜索,但没有找到任何内容。

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中有私有类, 但我没错。

1 个答案:

答案 0 :(得分:1)

请参见Java Language Specification §6.6.1

  

仅当可访问类型并且声明该成员或构造函数允许访问时,才可以访问引用类型的成员(类,接口,字段或方法)或类类型的构造函数。

     
      
  • 如果将成员或构造函数声明为公共,则允许访问。
  •   
  • 缺少访问修饰符的所有接口成员都是隐式公开的。
  •   
  • 否则,如果将成员或构造函数声明为受保护的,则仅当满足以下条件之一时才允许访问:

         
        
    • 对成员或构造函数的访问是在包含声明受保护的成员或构造函数的类的包内进行的。

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

    •   
  •   
  • 否则,如果使用包访问权限声明成员或构造函数,则仅当在声明了类型的包内部进行访问时才允许访问。

         

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

  •   
  • 否则,成员或构造函数被声明为私有,并且仅当在顶级类型(§7.6 ),其中包含成员或构造函数的声明。

  •   

(强调我的)

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

相关问题