0
\$\begingroup\$

Today i had discussion with my colleague about casting.

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?

\$\endgroup\$
  • \$\begingroup\$ 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? \$\endgroup\$ – Timothy Truckle Sep 7 '17 at 8:23
  • \$\begingroup\$ @TimothyTruckle I will pass it into generics ex. public class FooImpl<FooImpl> {} \$\endgroup\$ – regisik Sep 7 '17 at 8:28
  • \$\begingroup\$ 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. \$\endgroup\$ – Michael Lang Sep 8 '17 at 12:27
3
\$\begingroup\$

I think that both approaches are incorrect.

Why would you need to cast an object to its own type, while it is already typed to a type that inherits from its parent abstract type?

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

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.