PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] How can I reference instances of two classes?

 July 10, 2022     class, instance, java, object, reference     No comments   

Issue

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?


Solution

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.



Answered By - Vivere
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing