I want a function to return a type of the subclass its invoked from

Posted by Jay on Stack Overflow See other posts from Stack Overflow or by Jay
Published on 2010-05-04T22:12:47Z Indexed on 2010/05/04 22:18 UTC
Read the original article Hit count: 173

Filed under:
|
|

I want to have a function defined in a superclass that returns a value of the type 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". The compiler says that A is generic and I should specify the type. I guess it wants me to say "class A". 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", but this causes no complaints, so maybe that's just fine.

Is this the right way to do it? Is there a better way?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics