【问题标题】:Why won't my "private" keyword on var " first" work?为什么我在 var "first" 上的 "private" 关键字不起作用?
【发布时间】:2020-02-28 18:45:01
【问题描述】:

这些天我正在使用 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 中有私有类, 但我没有错。

【问题讨论】:

  • 为什么不能访问同一个类中的私有字段?您是否希望其类不使用私有字段?如果它自己的类无法访问它,那么谁应该能够使用它?
  • 如果您将main 方法移动到另一个类(就像在任何实际应用程序中一样),您确实会得到预期的错误。
  • 这个线程可能有助于理解。 stackoverflow.com/questions/4707504/…

标签: java data-structures


【解决方案1】:

Java Language Specification §6.6.1

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

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

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

  • 否则,如果成员或构造函数被声明为受保护,则仅当满足以下条件之一时才允许访问:

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

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

  • 否则,如果成员或构造函数声明为具有包访问权限,则仅当访问发生在声明类型的包内时才允许访问。

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

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

(强调我的)

由于您对first 的访问权属于同一顶级类型,因此您可以毫无问题地访问它、错误或其他任何事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 2023-01-30
    • 1970-01-01
    • 2016-11-08
    相关资源
    最近更新 更多