我期望获得内部类值为 8,但代码将其显示为“0”,为什么该值没有分配给内部类构造函数
public class Testit {
public static void main(String[] args) {
test obj = new test(9, 8);
test.test2 obj2 = obj.new test2();
obj2.show();
// TODO code application logic here
}
}
<小时/>
class test {
private int a;
private test2 d;
public test() {
a = 0;
}
public test(int aa, int b) {
a = aa;
d = new test2(b);
}
public class test2 {
private int b;
public test2() {
b = 0;
}
public test2(int bb) {
b = bb;
}
public void show() {
System.out.println("Outer variable " + a + " Inner Variable " + b);
}
}
}
最佳答案
你的错误在于 main 方法本身
public static void main(String[] args) {
test obj = new test(9, 8);
test.test2 obj2 = obj.new test2();
obj2.show();
// TODO code application logic here }
“Obj”是“test”类的新实例。但“obj2”是 test2 的一个新实例(即使您使用具有此新实例的 obj 引用)。
如果要检索构建值,请为 test.d 属性添加 getter,然后将“test.test2 obj2 = obj.new test2();
”更改为“test” .test2 obj2 = obj.getD();
"
您应该打印:
Outer variable 9 Inner Variable 8
关于java - 内部类构造函数未显示所需的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46142979/