Tuesday, December 13, 2011

Problem with Class Downcast

Sometime I think, I have gained a lot of knowledge in Java and I know lot of things in Java, but once in a while Java keeps pushing my believes to the corner and demonstrates it's superiority. Most of times it is basic java which deceives me. Here is my story.

Today one of my colleague asked one question and I did not have any answer for his question. The issue in concern belongs to the program written below.


class SuperClass {

void display(){
System.out.println("SuperClass Display.");
}

}

class SubClass extends SuperClass{

void display(){
System.out.println("SubClass Display.");
}


public static void main(String[] args){
SuperClass superClsInstance = new SuperClass();
SubClass subClsInstance = (SubClass) superClsInstance;
subClsInstance.display();
}

}

In this case I assumed downcast should happen without any issues and it should print message based on object instance. So in this case subClsInstance is referring to Object of SuperClass and it should print message mentioned below.
SuperClass Display

But no. It is not so simple.

It will throw ClassCastException. Heck Why? What have I done which made it throw such stupid and merciless exception? I am devastated and I do not even know basic of DownCasting, shame on me a 5 year experience java developer do not know such small thing. Anyways let me find out the reason for this behavior.

Hmmm, Interesting na.... I always knew that I am not very good in java and google and Sun have proved me right. As per the information available downcast is possible if and only if object created is a type of Class reference being downcasted to..

Lets take few example... Dog is an animal and An animal is dog only if it is a Dog. If you write same thing in the code so it would be...

Animal ani = new Dog();
Dog dg = (Dog) ani;

So in example listed above, Dog is an animal and it will down cast without problems as code is saying Dog is Dog...


Animal ani = new Animal();
Dog dg = (Dog) ani;
So here in example listed above, here Animal is an animal and it will not down cast as code is saying Animal is Dog...It can not be, we do not have information about Animal. This can be some other animal so Java can not assume anything. It will say that it does not have any idea about this animal so Buzz off.

In our case same thing is happening.We have created an object of SuperClass and asking it to tie up with SubClass. Java says no, do not bog me out with such stupid things and take care of your code better.

Oops java is right and I am wrong. Cool then I learnt something today and shared with you all. Hope you will learn and will not cause such stupid problems in code and will not screw up your interview. 


PS: Stay away from downcasting it is not only but also venomous and code safe.

No comments:

Post a Comment