# Java inheritance and generics [closed]

Our case: We have root class

abstract class RootFoo<R extends RooFoo> {
...
abstract R getThis();
}


and we implement method getThis in subclasses.

To save (in my opinion) unnecessary implementation getThis method in every subclass i showed my solution:

abstract class RootFoo<R extends RooFoo> {
...
R getThis() {
return (R) this;
}
}


Could you help me understand why my idea is wrong?

• The more interesting question is: why does the calling code has to know which Subclass of RootFoo will be returned? Why is'nt RootFoo getThis() enough? – Timothy Truckle Sep 7 '17 at 8:23
• @TimothyTruckle I will pass it into generics ex. public class FooImpl<FooImpl> {} – regisik Sep 7 '17 at 8:28
• Your idea is buggy because you could create classes ChildFoo extends RootFoo<Child2Foo> and Child2Foo extends RootFoo<ChildFoo>. Then the call of Child2Foo foo = new ChildFoo().getThis();would compile but throw a ClassCastException at runtime. – Michael Lang Sep 8 '17 at 12:27

The method getThis() is absolutely senseless, because if you have an instance of an object, it is typed by definition.