Reputation: 7706
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?
Upvotes: 2
Views: 80
Reputation: 5867
An abstract class can extend a class, and this is one of the rare situations where it could be useful.
abstract class AnimatedAbstractWalker extends Animate {
// class gets concrete methods from Animate
// and any abstract walk methods you want to add
// (this replaces the Walk interface)
}
class Cat extends AnimatedAbstractWalker {
// inherits standard animation implementation
// you must implement walking like a cat
}
class Dog extends AnimatedAbstractWalker {
// inherits standard animation implementation
// you must implement walking like a dog
}
Upvotes: 4
Reputation: 518
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 { ... }
Upvotes: 1
Reputation: 149185
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 {
...
}
Upvotes: 1
Reputation: 6248
Make a class that extends Animate, has no extra methods and implements Walks (It would be identical to Animate, but it would be yours)
public class MyAnimate extends Animate implements Walks{} // your own Animate
public class Cat extends MyAnimate {}
Upvotes: 3