我可以阻止实现接口吗? [英] Can I prevent an interface from being implemented?
问题描述
我有以下情况:
public interface A {
void doSomethingCool();
}
public interface B extends A {
void doSomethingVeryBCool();
}
public interface C extends A {
void doSomethingVeryCCool();
}
在我的应用程序中,我只能使用实现B或C的类。但是有部分代码,我想使用a.doSomethingCool(),因为我不知道(也不关心)使用哪种实现。
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.
我可以强制执行,只有B和C的实现吗?
或者阻止接口A被实现?
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.
编辑:然而,这确实意味着你不能做类似的事情
however, this does mean that you cannot do something like
A a = getA();
包裹外的
因为A无法解析。
outside the package because A cannot be resolved.
这篇关于我可以阻止实现接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!