I have this code:
public class Animate {} // external api <--------------
public class Cat extends Animate {} // written by me
public interface Walks {} // also written by me
How can I enforce that if something walks it has to be animate?
I have this code:
public class Animate {} // external api <--------------
public class Cat extends Animate {} // written by me
public interface Walks {} // also written by me
How can I enforce that if something walks it has to be animate?
On
You cannot.
An interface just defines an API and does not enforce an implementation.
If you want that something both implements an interface and extends an implementation, just create an abstract base class doing both and extend from there :
public class WalkingAnimate extends Animate implements Walks {
public abstract ... // abstracts methods from Walks
}
public class Cat extends WalkingAnimate {
...
}
On
Since class Animate is external you can't change it, but you can subclass it in your code:
public abstract class AnimatedWalk extends Animate implements Walk {}
In consequence, each class that inherits from your newly created AnimatedWalk is a Animate and has to implement Walk
public class Cat extends AnimatedWalk { ... }
An abstract class can extend a class, and this is one of the rare situations where it could be useful.