I want to have a function defined in a superclass that returns an instance of the subclass that is used to invoke the function. That is, say I have class A with a function plugh. Then I create subclasses B and C that extend A. I want B.plugh to return a B and C.plugh to return a C. Yes, they could return an A, but then the caller would have to either cast it to the right subtype, which is a pain when used a lot, or declare the receiving variable to be of the supertype, which loses type safety.
So I was trying to do this with generics, writing something like this:
class A<T extends A>
{
private T foo;
public T getFoo()
{
return foo;
}
}
class B extends A<B>
{
public void calcFoo()
{
foo=... whatever ...
}
}
class C extends A<C>
{
public void calcFoo()
{
foo=... whatever ...
}
}
This appears to work but it looks pretty ugly.
For one thing, I get warnings on class A<T extends A>
. The compiler says that A is generic and I should specify the type. I guess it wants me to say class A<T extends A<x>
. But what would I put in for x? I think I could get stuck in an infinite loop here.
It seems weird to write class B extends A<B>
, but this causes no complaints, so maybe that's just fine.
Is this the right way to do it? Is there a better way?