Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 734
dpelisek Avatar asked Oct 18 '12 11:10

dpelisek


2 Answers

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.

like image 156
siebz0r Avatar answered Sep 19 '22 10:09

siebz0r


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 {
    ...
}
like image 29
Jamie Avatar answered Sep 18 '22 10:09

Jamie