A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Beginning Java
Author
ClassCastException!!!
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
I like...
posted
May 29, 2008 23:36:00
0
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
posted
May 29, 2008 23:49:00
0
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
I like...
posted
May 30, 2008 00:11:00
0
Thanks amitabh
I agree. Here's the link:
http://jrebel.com/download
subject: ClassCastException!!!
Similar Threads
base class object problem
Which overloaded method?
Initializer
anonumous class
anonumous class
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter