Two Laptop Bag*
The moose likes Beginning Java and the fly likes ClassCastException!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ClassCastException!!!" Watch "ClassCastException!!!" New topic
Author

ClassCastException!!!

Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Hi All,

i try to do this..but i am getting this Exception
---------------------------------------------
class Base{
Base(){

}

private Base(int e){

}

public void print(){
System.out.println("base");
}
}


public class Sample extends Base{

public void print(){
System.out.println("drive");
}

public static void main(String[] args){

Sample sw=(Sample)new Base();//here i am doing downtype cast
sw.print();
}
}
-------------------------------------------------

but i am getting classcast exception!!!

so , my question is we can not type caste from super class to sub class?
(if yes..then how you will do this?)
please anyone explain me


Thanks & Regards,
seetharaman.v
amitabh mehra
Ranch Hand

Joined: Dec 05, 2006
Posts: 98
An object of supertype can not be downcasted to subtype object.

But, a reference of supertype that holds an object of subtype can be downcasted to the subtype reference.

Try this:
Base b = new Sample();
Sample sw = (Sample)b;
sw.print();
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Thanks amitabh
 
jQuery in Action, 2nd edition
 
subject: ClassCastException!!!