Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can the private member of an nested class be accessed by the methods of the enclosing class? [duplicate]

Tags:

java

Could anyone tell me about the accessing level of private member? I have been confused with this piece code for quite a long time: why the private member, k of Line class, can be accessed in "print" method of outter class?

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);
    }
}
like image 647
JoJo Avatar asked Nov 02 '13 22:11

JoJo


1 Answers

The rules are in the 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.

Here the member field k is declared in the class Line. When you access it in the print method, you are accessing it within the body of the top level class that encloses the declaration of that member.

The chapter on top level classes is here.

like image 96
Sotirios Delimanolis Avatar answered Oct 24 '22 23:10

Sotirios Delimanolis