The code works fine.
Why do you think that it should generate an exception?

-kolli

Rohan Amin

Greenhorn

Posts: 15

posted 7 years ago

Well i am not sure as to whether it should or should not throw exception. My guess is that it basically points to the sub class object and so even if it is being referred to by super class instance it gets downcasted. Well i just wanted to confirm whether my understanding is correct or not because this particular example has not been covered in the book but the topic actually starts with a similar example. Animal a = new Dog();

Rohan Amin wrote: .
The following compiles but later gives an exception.

.
The following compiles but gives no exception.
Please let me know about this.

The first code will definitely produce an exception..

This is because in SuperClass sc=new SuperClass() the reference variable sc refers to an object of SuperClass and it can not be cast to subtype object. The next code SuperClass sc=new SubClass() is correct as a reference variable of super type can refer to an object of subclass which is correct and hence it is also correct to cast the variable to the subtype(downcasting).
I hope this explains what you are seeking . Also correct me if I am wrong.

Well thats what i think. I think both the codes get past the compiler but at runtime the actual object is checked and so at the first case it fails whereas in the second case it works and so the program works.