Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
    Bookmark Topic Watch Topic
  • New Topic

Upcasting & Downcasting

 
Mohan Pakam
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Report post to moderator
Hi All! (my First post)

I have just started preparing for SCJP. I am bit confused about the Reference downcasting.

Example in KS/BB
class Animal { }
class Dog extends Animal { }
class Main {
public static void main(String [] args) {
Animal animal = new Animal();
Dog d = (Dog) animal; // compiles but fails later
}
}

Run-time Error:
Exception in thread "main" java.lang.ClassCastException: Animal cannot be cast to Dog
at Main.main(Main.java:6)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

So here the run-time error says the ClassCastException. But why did it fail?
a general knwledge, I know any animal can't be converted into a Dog. But wondering if this has a detailed explaination.


is that always downcasting fails at runtime?
 
Dj Lalotra
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Report post to moderator
Hi Mohan,

The answer to your question would be that Dog IS A Animal ,not Animal IS A Dog.
You can pass the object of a subclass(also the reference of a subclass) to the super class reference (Polymorphism),but not vice versa.
For eg.
Animal animal=new Animal();
Dog dog=new Dog();

animal=new Dog();
or
animal=dog;

But when you try to cast a Animal into a Dog i.e
Dog d = (Dog) animal;
It will throw run time exception 'ClassCastException'.

Always remember that you can never convert or cast a supertype into subtype.

Hope this would help.

Thanks.
DJ
 
Ankit Garg
Sheriff
Posts: 9579
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
Duplicate Topic, closing this one.
 
    Bookmark Topic Watch Topic
  • New Topic