I almost had a bit of a problem when turning an interface into an abstract class. Basically I wanted it to provide an implementation (which is why I changed it to abstract), however since it was mutable and therefore returning itself the abstract class caused problems for any code that implemented the derived class.
abstract class Abstract {
public Abstract mutableMethod (){
return createInstance ().doSomething();
}
}
abstract class Derived extends Abstract {
public Derived doSomething (){
...
}
}
class Main {
void poorMethod (){
// problem !!!
Derived derived = new Derived().doSomething();
}
}
However using templates you can eliminate this problem without overriding every method or making main look weirder in any way.
abstract class Abstract <DerivedClass extends Abstract> {
public DerivedClass mutableMethod (){
return createInstance ().doSomething();
}
}
abstract class Derived extends Abstract <Derived> {
public Derived doSomething (){
...
}
}
class Main {
void poorMethod (){
// no more problem !!!
Derived derived = new Derived().doSomething();
}
}