有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    规则在JLS chapter on accessibility

    Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

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

    关于顶级课程的章节是here