简体   繁体   中英

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. What is the best way to do that?

Is there any better way than create another abstract class extending MyAbstractClass and implementing 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. In the JavaDoc it should then state something like "to use this interface you need to extend from MyAbstractClass or provide your own implementation". 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 :

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

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. 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...

It sounds to me that you should drop the interface and replace it with the abstract class.

Cheers,

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