问题
The following Java programs compiles successfully.
I am expecting an error in the statement y.className = "No class name.";
since the private variable className are accessed outside its class.
class t {
public static void main(String[] r) {
Y y = new Y();
y.className = "No class name.";
y.echoClassName();
}
static class Y {
private String className = "Class Name is Y.";
public void echoClassName() {
System.out.println(className);
}
}
}
Why it shows no error?
回答1:
The scope of a private variable is the whole top level class in which it is enclosed, in your case t
. See for example JLS #6.6.1 (emphasis mine):
Otherwise, the member or constructor is declared private, and 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.
回答2:
Y is a nested class. which means it is embeeded in t class, where you run main. It is visible for its class only, but if you nest a class with private variable in class, then you can access this variable in this class.
If you put Y class in another file and create it in t, then you will get error of visibility. Since you are using nested class, everything is ok.
来源:https://stackoverflow.com/questions/26486427/accessing-private-variable-outside-its-class-in-java