Home > Software design >  How can I reference instances of two classes?
How can I reference instances of two classes?

Time:03-07

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?

CodePudding user response:

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.

  • Related