Casting a Super class object to its sub class
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   arun_krishnan
Posted On:   Thursday, October 27, 2005 01:12 PM

I have some sub classes which extends the same super class. I send this sub class(s) through object stream and read it as an object at the other end. Now since I know the super class I cast this read object to super class type.


I know the sub class name using getClass() method of object. But I want to cast this base class object to the specific sub class object to access subclass specific methods.

the idea would be as follows


subClassObject = (superObject.getClass()) superObject;

Any idea of doing this???


Thanks in advance....
arun

Re: Casting a Super class object to its sub class

Posted By:   Bogdan_Matasaru  
Posted On:   Friday, November 18, 2005 12:29 PM

There are several ways to do it but the simplest is the straightforward one:
If you want to cast in order to call subclass methods, then simply check that you have indeed the desired subclass with instanceof, then simply cast it.

if (superObject instanceof SubClass) {
SubClass subClassObject = (SubClass)superObject;
subClassObject.myMethod();
}

Re: Casting a Super class object to its sub class

Posted By:   Sean_Ruff  
Posted On:   Thursday, October 27, 2005 09:14 PM

If you really don't want to use the instanceof operator you could create overloaded methods which take as a parameter your sub class, then use reflection to invoke said methods.


Method meth = this.getClass().getMethod("performLogic",new Class[]{superObject.getClass()});
meth.invoke(this,new Object[]{superObject});


Of course you'll want to do some validation, and you would define multiple overloaded "performLogic" methods which take subclasses of your superObject class type.

Re: Casting a Super class object to its sub class

Posted By:   Almagest_FUTT  
Posted On:   Thursday, October 27, 2005 02:13 PM

No way.

Besides, you should use the instanceof operator rather than getClass().
About | Sitemap | Contact