title: Method chaining + inheritance don’t play well together?
body: <p><a href="https://stackoverflow.com/questions/551263/method-chaining-inheritance-dont-play-well-together">This question has been asked in a C++ context</a> but I'm curious about Java. The concerns about virtual methods don't apply (I think), but if you have this situation:</p>
  
  <pre><code>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
  }
  </code></pre>
  
  <p>In this sort of class hierarchy, is there any way to return <code>this</code> in a way that doesn't (effectively) upcast the the object type?</p>