【问题标题】:Why can the private member of an nested class be accessed by the methods of the enclosing class? [duplicate]为什么嵌套类的私有成员可以被封闭类的方法访问? [复制]
【发布时间】:2013-11-13 21:30:49
【问题描述】:

谁能告诉我私人会员的访问级别?这段代码我困惑了很久:为什么Line类的私有成员k可以在outter类的print方法中访问?

public class myClass {
    public static class Line{
        private double k;
        private double b;
        private boolean isVertical;

        public Line(double k, double b, boolean isVertical){
            this.k = k;
            this.b = b;
            this.isVertical = isVertical;
        }

    }

    public static boolean print(Line line){
        System.out.println(line.k);
    }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    规则在JLS chapter on accessibility

    否则,如果成员或构造函数声明为private,则 当且仅当访问发生在在 包含成员声明的顶级类(第 7.6 节)或 构造函数。

    这里的成员字段k 在类Line 中声明。当您在print 方法中访问它时,您正在在包含该成员声明的顶级类的主体中访问它

    顶级课程的章节是here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-23
      • 2011-01-14
      • 1970-01-01
      • 2023-03-29
      • 2010-12-12
      • 2014-04-02
      • 1970-01-01
      • 2015-07-16
      相关资源
      最近更新 更多