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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With