17

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);
    }
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
JoJo
  • 1,377
  • 3
  • 14
  • 28

1 Answers1

44

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724