如何引用两个类的实例?

发布于 01-12 08:27 字数 467 浏览 1 评论 0原文

我有两个类,比如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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

以歌曲疗慰2025-01-19 08:27:31

您正在 ClassB 中创建 ClassA 的实例。

如果您的代码类似于:

ClassA a = new ClassA();
ClassB b = new ClassB();
a.setCharacterA('y');

那么,ClassB 中的 ClassA 的字符不会改变,因为有两个不同的实例。您需要做的就是通过构造函数或setter将ClassA的实例传递到ClassB中,例如:

public ClassB {
    private ClassA obj;

    public ClassB(ClassA obj) {
        this.obj = obj;
    }
}

然后您可以按如下方式使用它们:

ClassA a = new ClassA();
ClassB b = new ClassB(a);
a.setCharacterA('y');

现在,字符发生变化由于您将使用相同的实例,因此也会反映在 ClassB 中。

You are creating an instance of ClassA in ClassB.

If your code is something like:

ClassA a = new ClassA();
ClassB b = new ClassB();
a.setCharacterA('y');

Then, the character of ClassA in ClassB won't change since there are two different instances. What you need to do is to pass the instance of ClassA in ClassB via constructor or a setter, such as:

public ClassB {
    private ClassA obj;

    public ClassB(ClassA obj) {
        this.obj = obj;
    }
}

then you can use them as follows:

ClassA a = new ClassA();
ClassB b = new ClassB(a);
a.setCharacterA('y');

Now, the character change will also reflect in ClassB since you will use the same instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文