views:

416

answers:

5

This question has been asked in a C++ context but I'm curious about Java. The concerns about virtual methods don't apply (I think), but if you have this situation:

abstract class Pet
{
    private String name;
    public Pet setName(String name) { this.name = name; return this; }        
}

class Cat extends Pet
{
    public Cat catchMice() { 
        System.out.println("I caught a mouse!"); 
        return this; 
    }
}

class Dog extends Pet
{
    public Dog catchFrisbee() { 
        System.out.println("I caught a frisbee!"); 
        return this; 
    }
}

class Bird extends Pet
{
    public Bird layEgg() {
        ...
        return this;
    }
}


{
    Cat c = new Cat();
    c.setName("Morris").catchMice(); // error! setName returns Pet, not Cat
    Dog d = new Dog();
    d.setName("Snoopy").catchFrisbee(); // error! setName returns Pet, not Dog
    Bird b = new Bird();
    b.setName("Tweety").layEgg(); // error! setName returns Pet, not Bird
}

In this sort of class hierarchy, is there any way to return this in a way that doesn't (effectively) upcast the the object type?

+3  A: 

No, not really. You could work around it by using covariant return types (thanks to McDowell for the correct name):

@Override
public Cat setName(String name) {
    return (Cat) super.setName(name);
}

(Covariant return types are only in Java 5 and above, if that's a concern for you.)

Michael Myers
+6  A: 

How about this old trick:

abstract class Pet<T extends Pet>
{
    private String name;
    public T setName(String name) { this.name = name; return (T) this; }        
}

class Cat extends Pet<Cat>
{
    /* ... */
}

class Dog extends Pet<Dog>
{
    /* ... */
}
Rasmus Faber
+1, expressed more concisely than I did. But given how long java generics have been around, how old a trick could it be?
Steve B.
aha, I figured there would be something with generics, just didn't know what. Thanks!
Jason S
@Steve B: It is not old in Java (actually, I don't think I have seen it used in Java), but it has been used in C++ for a long time.
Rasmus Faber
Hmmm. Could you add an upcasting and downcasting example also? e.g. Pet<?> pet = c; ((Cat)pet).catchMice(); (do I have that right?)
Jason S
+4  A: 

It's a bit convoluted, but you can do this with generics:

  abstract class Pet< T extends Pet > {
    private String name;

    public T setName( String name ) {
     this.name = name;
     return (T)this;
    }

    public static class Cat extends Pet< Cat > {
     public Cat catchMice() {
      System.out.println( "I caught a mouse!" );
      return this;
     }
    }

    public static class Dog extends Pet< Dog > {
     public Dog catchFrisbee() {
      System.out.println( "I caught a frisbee!" );
      return this;
     }
    }

    public static void main (String[] args){
     Cat c = new Cat();
     c.setName( "Morris" ).catchMice(); // error! setName returns Pet, not Cat
     Dog d = new Dog();
     d.setName( "Snoopy" ).catchFrisbee(); // error! setName returns Pet, not Dog
    }

}
Steve B.
+1  A: 
public class Pet<AnimalType extends Pet> {

 private String name;
    public AnimalType setName(String name) {
       this.name = name; return (AnimalType)this; 
    }        
}

and

public class Cat extends Pet<Cat> {

    public Cat catchMice() {return this;}

    public static void main(String[] args) {
     Cat c = new Cat().setName("bob").catchMice();
    }

}

@Steve B. - +1, bet me to it!
+3  A: 

If you want to avoid unchecked cast warnings from your compiler (and don't want to @SuppressWarnings("unchecked")), then you need to do a little more:

First of all, your definition of Pet must be self-referential, because Pet is always a generic type:

abstract class Pet <T extends Pet<T>>

Secondly, the (T) this cast in setName is also unchecked. To avoid this, use the "getThis" technique in the excellent Generics FAQ by Angelika Langer:

The "getThis" trick provides a way to recover the exact type of the this reference.

This results in the code below, which compiles and runs without warnings. If you want to extend your subclasses, then the technique still holds (though you'll probably need to genericise your intermediate classes).

The resulting code is:

public class TestClass {

  static abstract class Pet <T extends Pet<T>> {
    private String name;

    protected abstract T getThis();

    public T setName(String name) {
      this.name = name;
      return getThis(); }  
  }

  static class Cat extends Pet<Cat> {
    @Override protected Cat getThis() { return this; }

    public Cat catchMice() {
      System.out.println("I caught a mouse!");
      return getThis();
    }
  }

  static class Dog extends Pet<Dog> {
    @Override protected Dog getThis() { return this; }

    public Dog catchFrisbee() {
      System.out.println("I caught a frisbee!");
      return getThis();
    }
  }

  public static void main(String[] args) {
    Cat c = new Cat();
    c.setName("Morris").catchMice();
    Dog d = new Dog();
    d.setName("Snoopy").catchFrisbee();
  }
}
paulcm