1

I have an abstract class Animal:

public abstract class Animal {
    public Animal eat() {
        return this;
    }
}

I have a Cat class wich extends Animal:

public class Cat extends Animal {
    public Cat run() {
        return this;
    }
    public Cat sleep() {
        return this;
    }
}

And with that, I want to be able to do that:

Cat cat = new Cat();
cat.run()
    .eat()
    .sleep();

But unfortunately I cannot because the eat() method return an instance of Animal and there is not sleep() method in Animal class.

An ugly solution could be to cast the Animal instance returned by eat() method in Cat type like this:

Cat cat = new Cat();
((Cat) cat.run()
    .eat())
    .sleep();

But I don't want to do that because in my real case I am chaining a lots of methods.

Question: Is there a way to force method of parent class to return child instance?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Thibaud Sowa
  • 402
  • 4
  • 19
  • 1
    Why don't you override `eat()` inside cat as `public Cat eat()`? That will return a cat. – TayTay Nov 04 '15 at 14:40
  • 1
    alternatively you can make Animal an interface – cristianhh Nov 04 '15 at 14:41
  • Also see [What is a covariant return type?](http://stackoverflow.com/questions/1882584/what-is-a-covariant-return-type). – Andy Thomas Nov 04 '15 at 14:43
  • Overriding is not an option in my case, because I have a lots of 'mini' helper methods in my abstract class that I want to use with my child instance. – Thibaud Sowa Nov 04 '15 at 14:49
  • Actually as Sotirios Delimanolis says, the question is duplicated. This solution solves my problem. Sorry http://stackoverflow.com/a/1069605/5499650 – Thibaud Sowa Nov 04 '15 at 15:25
  • @ThibaudSowa It solves your problem for one level of inheritance, but you won't be able to extend `Cat` and do the same thing for a subclass without making `Cat` generic. However, using generics to do this is ridiculous anyway. There are no examples in JDK of generics being used in this way, with good reason. The idiomatic solution is to use overriding. – Paul Boddington Nov 04 '15 at 15:29
  • @Paul Boddington thanks for this information! But in my case, I will never extend my `Cat` class, so there is no problem... But you are right to specify this for other people. – Thibaud Sowa Nov 04 '15 at 15:34
  • @PaulBoddington The overriding solution is also provided in the linked question. – Sotirios Delimanolis Nov 04 '15 at 15:45
  • @Paul You should comment and vote on those answers with these details. – Sotirios Delimanolis Nov 04 '15 at 15:58

0 Answers0