如何引用两个类的实例?
我有两个类,比如A类和B类。
对于B类,它使用A类的实例变量。
例如,在A类中:
public ClassA {
numA = 0;
characterA = 'x';
}
然后,在创建B类的对象时,我需要使用num和character信息。
例如,在B类中:
public ClassB {
ClassA obj = new ClassA();
numB = obj.getNumA();
characterB = obj.getCharacterA;
}
问题是,如果我使用setCharacterA('o')将characterA更改为'o',则该值(即characterB)将不会在ClassB中更新。
有没有办法通过使用 ClassA 中的 setter 来更新 ClassB 中的值?
I have two classes, say Class A and Class B.
For Class B, it uses the Instance Variables of Class A.
For instance, in Class A:
public ClassA {
numA = 0;
characterA = 'x';
}
Then, when creating an object of ClassB, I need to use the num and character info.
For instance, in Class B:
public ClassB {
ClassA obj = new ClassA();
numB = obj.getNumA();
characterB = obj.getCharacterA;
}
The problem is, if I change the characterA to 'o' using setCharacterA('o'), the value (i.e. characterB) will not be updated in ClassB.
Is there a way where I can update the value in ClassB also, by using setters in ClassA?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您正在
ClassB
中创建ClassA
的实例。如果您的代码类似于:
那么,
ClassB
中的ClassA
的字符不会改变,因为有两个不同的实例。您需要做的就是通过构造函数或setter将ClassA
的实例传递到ClassB
中,例如:然后您可以按如下方式使用它们:
现在,字符发生变化由于您将使用相同的实例,因此也会反映在 ClassB 中。
You are creating an instance of
ClassA
inClassB
.If your code is something like:
Then, the character of
ClassA
inClassB
won't change since there are two different instances. What you need to do is to pass the instance ofClassA
inClassB
via constructor or a setter, such as:then you can use them as follows:
Now, the character change will also reflect in
ClassB
since you will use the same instance.