Amol Amol - 2 months ago 4x
Java Question

Superclass subclass type casting strange behavior

I am facing a strange behavior in type casting in superclass and subclass.

When type casting in spring's

method is done it doesn't cause any error but when I type cast manually it fails with a

Spring beans
type cast:

Listing l1=(Listing)det.getBean("list1"); // legal

My normal inheritance type cast

Object o=new Object();
circle c=(circle)o; //ClassCastException

Can someone point out the difference between the two?


Presumably the list1 bean in the first snippet is actually a Listing object, and you are just casting to store it in a Listing reference.

In the second snippet, o is a java.lang.Ojbect. It is not a circle instance, so the cast fails in runtime.