直到今天我才意识到这一点,但在 Java 中,私有字段在内部类中并不是真正私有的。您可以实例化一个类并访问这些字段,就好像它们是公共的一样。我的问题是为什么这是在 Java 中完成的?哪些设计决策导致了封装的中断?允许这样做有什么好处吗?
public class test {
public static void main(String[] args) {
Inner inner = new Inner();
inner.data = "TEST";
System.out.println(inner.data);
Inner1 inner1 = new Inner1();
inner1.data = "TEST";
System.out.println(inner1.data);
new test();
}
public test() {
Inner2 inner2 = new Inner2();
inner2.data = "TEST";
System.out.println(inner2.data);
Inner3 inner3 = new Inner3();
inner3.data = "TEST";
System.out.println(inner3.data);
}
private final class Inner3 {
private String data;
public String getData() {
System.out.println("Inner3.getData()");
return data;
}
public void setData(String data) {
System.out.println("Inner3.setData(String)");
this.data = data;
}
}
private class Inner2 {
private String data;
public String getData() {
System.out.println("Inner2.getData()");
return data;
}
public void setData(String data) {
System.out.println("Inner2.setData(String)");
this.data = data;
}
}
private static class Inner1 {
private String data;
public String getData() {
System.out.println("Inner1.getData()");
return data;
}
public void setData(String data) {
System.out.println("Inner1.setData(String)");
this.data = data;
}
}
private static final class Inner {
private String data;
public String getData() {
System.out.println("Inner.getData()");
return data;
}
public void setData(String data) {
System.out.println("Inner.setData(String)");
this.data = data;
}
}
}