Question about extended instances sharing the same one super instance.
Hello,
My case is that I have a very big class. Now I want to decompose this big class into two smaller classes A and B. But because class A and class B need to share some common attributes, both classes can update these attributes and the other can see the updated values.
I come up with the design that there is a super class(having these common attributes), and two extended class A and class B. And my question is how can I reference instances of class A and B to the same super class instance so that when class A update its super class attributes, class B is also updated and vice versal. Or is there any different sufficient design for this situation?
Thank you every much for your help.
Tu
It is a web application using java bean classes. May be an example can make it clear.
Common attributes(which class A and B can set or get to the same attribute):
Super class has these attributes:
String name;
int number;
Class A and class B extend from the super class
classA.setName("me");
classB.getName(); //should return "me" here
classB.setName("you");
classA.getName(); //should return "you" here
--
What can I do to archiv this?
> That can't be done unless the attributes are static,
> and you don't want that. Your design is very weird.
>> This class has about 2200 line.
The really scary part is that those questions seldom come from people "learning Java" but often from people "working on web apps".
> I'm sure there are other parts of the code (e.g.
> static methods or methods which could be made static)
> which you could transfer into other classes, but I'm
> quite sure the attributes should stay where they are.
Put the data into a shared container instance, where it probably belongs anyway.
> I come up with the design that there is a super
> class(having these common attributes), and two
> extended class A and class B. And my question is how
> can I reference instances of class A and B to the
> same super class instance so that when class A update
> its super class attributes, class B is also updated
> and vice versal.
First you neeed to get straight the difference between class variables (static) and instance variables (non-static). If you're talking class variables, then you don't need to do anything special. There's one copy shared by the parent class and all child classes. If you're talking instance variables, then each and every instance of the parent class and of the child classes has its own copy.