I have a Spring bean (ChildBean extends Parent
) which is extending an abstract class (Parent implements Runnable
).
public abstract class Parent implements Runnable {
public final void run() {
// some code
}
public int overridenFunct() {
// some code
}
}
Child bean class variant which causes ClassCastException:
@Transactional
@Scope("prototype")
@Service("beanName")
public class ChildBean extends Parent {
@Override
public int overridenFunct() {
// some diff code
}
}
Everything works fine until I override public non-abstract method from parent class in child bean. After that a ClassCastException is thrown when I'm trying to create an instance of that bean.
Parent p = (Parent) appContext.getBean("beanName");
Bean object returned by getBean()
is a ChildBean
class instance (checked with debugger). Why does casting ChildBean
object to its abstract parent class Parent
not work?
So, without an overridenFunct()
implemented in ChildBean
everything works fine.
Could someone please tell what is the problem here?
UPDATE:
Changing method overridingFunct()
to protected fixes the issue. But what if I need to override a public method? Is that allowed? I'm using Spring 3.2.8
UPDATE2:
Well, I didn't get to the point why overriding public method in abstract parent causes ClassCastException. As the resolution I did the following: created an interface with all public methods with common logic, an abstract class, which implements that interface and all "common" methods. Then all the child beans are extended from that abstract class, implementing its specific logic.