I have a class heirarchies defined as follows:
class ClassA{}
class ClassB extends ClassA{}
class BaseClass
{
public <T extends ClassA> T method1(){ return null; }
public <T extends ClassA> T method2(T param1){ return null; }
}
I want to extend the above BaseClass and override the implementations of method1
and method2
, but I'm struggling with the method signature in the DerivedClass. Here's what I tried:
class DerivedClass extends BaseClass
{
@Override
public ClassB method1() {return new ClassB();}
@Override
public ClassB method2(ClassB param1) {return new ClassB();}
}
For method1
, I get the warning:
Type safety: The return type ClassB for method1() from the type DerivedClass needs unchecked conversion to conform to T from the type BaseClass
For method2
, I get the following error:
The method method2(ClassB) of type DerivedClass must override or implement a supertype method
How do I resolve this?
Edit: I had to refactor the design and put the generic type on the BaseClass
instead of each individual methods, so that such scenario doesn't occur.