dcsimg
ClassCastException when casting Array from Subclass to Super Class
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   S_Luk
Posted On:   Tuesday, February 21, 2006 01:19 AM

I am getting ClassCastException with trying to do the following A SuperClass which cannot be changed. A SubClass which extends SuperClass. class SomeOtherClass { public SubClass[] getSubArray() { SuperClass[] superArray = this.getSuperArray(); SubClass[] subArray = new SubClass[superArray.length]; for(int i = 0; i < superArray.length; i++) { SuperClass superObj = new SubClass(); superObj = superArray[i]; subArray[i] = (SubClass) superObj; } } } A ClassCastException is thrown at subArray[i] = (SubClass) superObj; Any other way of doing casting of array between Sup   More>>

I am getting ClassCastException with trying to do the following




A SuperClass which cannot be changed.

A SubClass which extends SuperClass.



class SomeOtherClass {

			
public SubClass[] getSubArray() {
SuperClass[] superArray = this.getSuperArray();
SubClass[] subArray = new SubClass[superArray.length];
for(int i = 0; i < superArray.length; i++) {
SuperClass superObj = new SubClass();
superObj = superArray[i];
subArray[i] = (SubClass) superObj;
}
}


}


A ClassCastException is thrown at subArray[i] = (SubClass) superObj;


Any other way of doing casting of array between Super and Sub Class? Thanks.

   <<Less

Re: ClassCastException when casting Array from Subclass to Super Class

Posted By:   ankush_purwar  
Posted On:   Tuesday, February 21, 2006 01:26 PM

It seems there is some problem with your code.

SuperClass superObj = new SubClass();
superObj = superArray[i]; /* This line will loose the object of subclass that you hava create in first step. */
subArray[i] = (SubClass) superObj;

I hope you understands now

Re: ClassCastException when casting Array from Subclass to Super Class

Posted By:   Almagest_FUTT  
Posted On:   Tuesday, February 21, 2006 09:02 AM

You have Objects in your superArray that are not instances of SubClass. You can't cast in this case.
About | Sitemap | Contact