仅当类继承自特定类时才能够实现接口
我正在用java编程。 假设我有一个“MyInterface”接口和一个“MyClass”抽象类。
我想确保每个实现“MyInterface”接口的类都是从“MyClass”继承的。 从 MyClass 继承的类完全能够不实现“MyInterface”接口。
这可能吗?谢谢。 如果我的英语不好,我很抱歉,但我是法国人。
I'm programming with java.
Let's say I have an "MyInterface" interface, and a "MyClass" abstract class.
I want to ensure that every class implementing the "MyInterface" interface is inherited from "MyClass".
An inherited class from MyClass is perfectly able to NOT implement the "MyInterface" interface.
Is this possible ? Thanks.
I'm sorry if my english is bad but I'm french.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有。那是不可能的。接口的全部意义在于使来自不同继承层次结构的类可以实现对预定义功能集的支持。
Nope. That's not possible. The whole point of an interface is to make it so that classes from different inheritance hierarchies can implement support for a pre-defined set of capabilities.
AFAIK,你不能直接这样做。
如果有帮助的话,泛型可以让您这样说:
因此,您只能使用 MyClass 和 MyInterface 参数调用 foo()。
或者,为什么不拥有两个抽象基类呢?
然后,使用 MyInterfaceClass 而不是 MyInterface。
或者,如果您只关心容器,请编写自己的容器:
然后,每当您犯错误时,您都会收到弃用警告。
但我的问题仍然是——你想解决什么问题?您可以使用更具描述性的名称来代替“类”和“接口”吗?也许正确的解决方案是完全不同的东西..
AFAIK, you can't do this directly.
Generics let you say something like this, if it helps:
So, you can only call foo() with parameters that are both MyClass and MyInterface.
Or, why not have two abstract base classes?
Then, use MyInterfaceClass instead of MyInterface.
Or, if you just care about containers, write your own:
Then, you will get a deprecation warning any time you make a mistake.
But my question remains - what problem are you trying to solve? Can you use more descriptive names instead of "Class" and "Interface"? Perhaps the right solution is something completely different..
不,这是不可能的。任何类都可以实现
MyInterface
。无法将实现者限制为MyClass
的子类。如果您确实需要这样的限制,我认为您将不得不不使用接口,而是使用
MyClass
代替接口。No, it is not possible. Any class can implement
MyInterface
. There is no way to limit implementors to subclasses ofMyClass
.If you really need a limitation like that I think you'll be stuck with having to not use an interface and instead use
MyClass
in place of an interface.