在我的主类中,我有一个名为 Shape 的内部类,它扩展了 JButton。这个内部类有一个名为 CUBE 的私有(private) char 变量。
我为它编写了 getter 和 setter。我注意到在 main 方法中,没有使用:
(instance of Shape).getCUBE();
我可以通过以下方式访问它:
(instance of Shape).CUBE
发生这种情况是因为 CUBE 最终与 main 属于同一个类吗?
我是否有必要为这样的内部类编写 getter 和 setter?
最佳答案
Does this happen because CUBE is ultimately in the same class as main?
不,它有效是因为语言规范说它有效。就 JVM 而言,它将作为一个单独的类结束,但将创建额外的包级方法以允许外部类看起来违反正常规则。
语言规范的相关部分在 6.6.1 中:
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.
(强调我的。)
所以实际上,即使是 peer 嵌套类也可以访问私有(private)成员。示例代码:
public class Test {
public static void main(String[] args) {
First first = new First(10);
Second second = new Second(first);
System.out.println(second.getValueFromFirst());
}
private static class First {
private final int value;
private First(int value) {
this.value = value;
}
}
private static class Second {
private final First first;
private Second(First first) {
this.first = first;
}
private int getValueFromFirst() {
return first.value;
}
}
}
如果您查看生成的类(使用 javap -c Test$First
和 javap -c Test$Second
,您会看到合成方法 由编译器生成。
关于java - 访问内部对象类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10574013/