java为什么嵌套类的私有成员可以被封闭类的方法访问?
有人能告诉我私人会员的访问级别吗?很长一段时间以来,我一直对这段代码感到困惑:为什么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);
}
}
# 1 楼答案
规则在JLS chapter on accessibility
这里,成员字段
k
在类Line
中声明。当您在print
方法中访问它时,您是在顶级类的主体内访问它,该顶级类包含该成员的声明关于顶级课程的章节是here