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?