我真的不明白您在这里要做什么,并且您的代码无法编译。我在下面创建了一个带有注释的代码的工作示例。
这回答了你的问题了吗?
public class Main {
//Test method to instantiate a new B
public static void main(String[] args) {
B b = new B();
}
}
class A {
int a = 0;
public A() {
a =1;
}
}
class B {
public B() {
A a = new A();
//Print first object reference
System.out.println("First object reference assigned to a: " + a.toString());
//You cannot instantiate the same field/variable twice.
// However, you can change the object reference as below
a = new A();
//Print second object reference
System.out.println("Second object reference assigned to a: " + a.toString());
//As you can see, the object
// reference points at the new Instance of A when creating a
// new instance of A and assigning the reference to field a
}
}
如果您运行它,您的输出将如下所示:
First object reference assigned to a: A@750159
Second object reference assigned to a: A@1abab88