I have trouble subclassing a very simple class that has methods returning the initial class too.
public class MyClass {
public MyClass(){
}
public MyClass filterOn(String something){
MyClass result=new MyClass();
result.doSomethingUsingThisInstance(this, something);
return result;
}
}
public class MySubClass extends MyClass{
....
}
Ok, now if I want to call this:
MySubClass subClass=new MySubClass();
MySubClass subClass2=(MySubClass)subClass.filterOn("Hello World");
Then I have a java.lang.ClassCastException:cannot cast MyClass to MySubClass
How to prevent this?
Override the
filterOn()
method to create the instance you wish inMySubClass
:You could also avoid duplication in
filterOn()
method by introducing a method inMyClass
to create a instance of the current class that we override in subclass:Now Sub class only override createSpecificInstance() :