Can I prevent an interface from being implemented?

2019-03-04 05:12发布

问题:

I have the following Situation:

public interface A {
    void doSomethingCool();
}

public interface B extends A {
    void doSomethingVeryBCool();
}
public interface C extends A {
    void doSomethingVeryCCool();
}

In my application I can only use classes implementing B or C. But there are parts of the code, where I want to use "a.doSomethingCool()", because I don't know (and don't care) which implementation is used.

Can I enforce, that there are only implementations of B and C? Or prevent the interface A from being implemented?

回答1:

You cannot directly enforce the interface not being implemented, however you can make the interface package-local:

interface A {...} //no public

This way classes outside that package cannot see the interface.

EDIT: however, this does mean that you cannot do something like

A a = getA();

outside the package because A cannot be resolved.



标签: java oop