Can two Java interfaces be mutually exclusive?
•
Java
I have two interfaces that should be excluded:
interface Animal{} interface Cat extends Animal{} interface Bird extends Animal{}
How to prevent classes that implement cat and bird interfaces?
class Impossible implements Cat,Bird{}
Solution
Here you have a clear hierarchy - a root with branches, and a node (class, interface, anything) cannot be on multiple branches To achieve this, use abstract classes instead of interfaces
Interfaces can be used when some cross - cutting aspects can be shared between any class in the hierarchy and no two interfaces are mutually exclusive
Example:
public abstract class Animal; public interface CanFly; public interface CanHunt; public abstract class Cat extends Animal implements CanHunt; public abstract class Bird extends Animal implements CanFly; public class Vulture extends Bird implements CanHunt; //also CanFly because of Bird
At least one person has considered this issue: http://instantbadger.blogspot.co.uk/2006/10/mutually-exclusive-interfaces.html
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码