Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException!!!

 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks amitabh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic