简体   繁体   English

Java:强制实现接口以扩展抽象类

[英]Java: Force implementation of interface to extend abstract class

I have several classes implements interface MyInterface and I want all of them to extend abstract class MyAbstractClass. 我有几个类实现接口MyInterface,我希望它们都扩展抽象类MyAbstractClass。 What is the best way to do that? 最好的方法是什么?

Is there any better way than create another abstract class extending MyAbstractClass and implementing MyInterface? 有没有比创建扩展MyAbstractClass和实现MyInterface的另一个抽象类更好的方法?

(I swear I haven't found any question like this before I posted) (我发誓在发布之前我没有发现任何这样的问题)

The cleanest solution would be to define such a requirement in the JavaDoc of the interface. 最干净的解决方案是在接口的JavaDoc中定义这样的要求。 In the JavaDoc it should then state something like "to use this interface you need to extend from MyAbstractClass or provide your own implementation". 在JavaDoc中,它应该声明类似“使用此接口,您需要从MyAbstractClass扩展或提供您自己的实现”。 This way the programmer is responsible for the implementation. 这样程序员就负责实现。 Remember that this is a sociological problem which you try to solve technicality. 请记住,这是一个社会学问题,你试图解决技术问题。

Another 'solution' would be to drop the interface and use an abstract class. 另一个“解决方案”是删除接口并使用抽象类。 Implementing the interface in the abstract class wouldn't make sense here. 在抽象类中实现接口在这里没有意义。

You could define MyAbstractClass to implement MyInterface , and then make all of your other classes extend MyAbstractClass : 您可以定义MyAbstractClass来实现MyInterface ,然后使所有其他类扩展MyAbstractClass

public abstract class MyAbstractClass implements MyInterface {
    ...
}

public class OneOfSeveral extends MyAbstractClass {
    ...
}

You can't force all your concrete classes to extend MyAbstractClass in any other way than actually changing their definitions from 除了实际更改其定义之外,您不能强制所有具体类以任何其他方式扩展MyAbstractClass

class A implements MyInterface

to

class A extends MyAbstractClass

and of course 而且当然

abstract class MyAbstractClass implements MyInterface

You don't need another abstract class as you write, though. 但是,在编写时不需要另一个抽象类。

Edit : Regarding your comment below: "I want the other way that every implementation of MyInterface extends MyAbstractClass" - you cannot enforce that sensibly. 编辑 :关于你的评论如下:“我想要MyInterface的每个实现扩展MyAbstractClass的另一种方式” - 你不能明智地强制执行。 You can define another interface that MyInterface extends and call that MyAbstractClassInterface if you want but you still won't be able to enforce your existing classes extend an abstract class implementing this latter interface, although they will of course have to actually implement the methods defined in this interface... 您可以定义MyInterface扩展的另一个接口,如果需要,可以调用MyAbstractClassInterface但是您仍然无法强制执行现有类扩展实现后一个接口的抽象类,尽管它们当然必须实际实现在这个界面......

It sounds to me that you should drop the interface and replace it with the abstract class. 听起来你应该删除界面并用抽象类替换它。

Cheers, 干杯,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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