I have two interfaces that should exclude each other:
interface Animal{}
interface Cat extends Animal{}
interface Bird extends Animal{}
How can I prevent the implementation of a class that implements both Cat
and Bird
interfaces?
class Impossible implements Cat, Bird{}
Finally a dirty solution:
public interface Animal<BEING extends Animal> {}
public interface Cat extends Animal<Cat> {}
public interface Bird extends Animal<Bird> {}
public class CatBird implements Cat, Bird {} // compiler error
public interface CatBird extends Cat, Bird {} // compiler error
CatBird cant be implemented because:
The interface Animal cannot be implemented more than once with different arguments: Animal<Bird> and Animal<Cat>
Here you have a clear hierarchy - a root with branches, and clearly a node (class, interface, whatever) cannot be on more than one branch. In order to enforce this, use abstract classes instead of interfaces.
Interfaces may be used when there is some cross-cutting aspect which may be shared between any of the classes in your hierarchy, and where 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 other has considered this problem: http://instantbadger.blogspot.co.uk/2006/10/mutually-exclusive-interfaces.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With