简体   繁体   中英

Can I prevent an interface from being implemented?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM