IntelliJ open source
[Logo] JavaRanch » JavaRanch Saloon
  Search | FAQ | Recent Topics | Hot Topics
Register / Login


Reply Bookmark it! Watch this topic JavaRanch » Forums » Engineering » OO, Patterns, UML and Refactoring
 
RSS feed
 
New topic
Author

Question on implentation inheritance

Kavya Das
Greenhorn

Joined: Jan 06, 2010
Messages: 7

Can we design a super class to have a instance variable whose type is one of its sub classes?

Logically, this may sound stupid, but programmatically its possible right?

I have an interface Say UserInterface. I have 2 implementations of this interface UserImpl1 and UserImpl2.

I have to invoke the method from one of these impl based on some logic. And in some cases, I may have to call the methods from both the impl one after the other.

So, what I have done is I wrote one more class, Say UserImpl3 that implements the interface and the clients would be invoking the methods on this class. Methods in this class will have the logic to determine whether the method from the UserImpl1 has to be called or UserImpl2 or from both.

I am somewhat not comfortable writing the UserImpl3 at the same level as the UserImpl1 and UserImpl3.

I thought of gng for the adapter pattern with the hierarchy as UserImpl3 (only this implements the interface now) as the super class and UserImpl1 and UserImpl2 as its subclasses. So, the question is can we have the super class call the methods from the sub classes by defining the sub class objects as its instance variables?

Please advice.
Venkat Divvela
Ranch Hand

Joined: Apr 16, 2008
Messages: 90

Can we design a super class to have a instance variable whose type is one of its sub classes?


Yes a super class can have one of its sub classes as instance variable.

I am somewhat not comfortable writing the UserImpl3 at the same level as the UserImpl1 and UserImpl3.


For the given interface UserInterface you may have 3 implementations UserImpl1 , UserImpl2 , UserImpl3. UserImpl3 can have instance variables UserImpl1 and UserImpl2



So, the question is can we have the super class call the methods from the sub classes by defining the sub class objects as its instance variables?


Yes super class can have sub classes as instance variables and call their methods.


SCJP 5.0, SCWCD 5, preparing for SCDJWS
latha paul
Greenhorn

Joined: Mar 01, 2007
Messages: 3

If we see the examples of Adapter pattern we can observe the "sub class objects as super class instance variables"

 
 
 
Reply Bookmark it! Watch this topic JavaRanch » Forums » Engineering » OO, Patterns, UML and Refactoring
 
RSS feed
 
New topic
hibernate profiler

.