Amol Amol - 3 months ago 11
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

getBean()
method is done it doesn't cause any error but when I type cast manually it fails with a
ClassCastException
:

Spring beans
getBean()
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?

Answer

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.

Comments