Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
    Bookmark Topic Watch Topic
  • New Topic

Upcasting & Downcasting  RSS feed

Mohan Pakam
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(
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
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();

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.

Ankit Garg
Posts: 9610
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
Duplicate Topic, closing this one.
Consider Paul's rocket mass heater.
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!