Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make two Java interfaces mutually exclusive?

Tags:

java

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{}
like image 344
Grim Avatar asked Oct 25 '13 09:10

Grim


2 Answers

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>

like image 200
Grim Avatar answered Nov 08 '22 10:11

Grim


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

like image 24
NickJ Avatar answered Nov 08 '22 11:11

NickJ