Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

abstract classes and interfaces best practices in java

So you've got an interface and an abstract class that implements a subset of the methods in the interface. You've also got some classes that inherit the abstract class and give implementations of the methods the abstract class doesn't give.

So what's the best practice here? I'm talking about issues like:

1) Should the abstract class implement the interface or should its child classes? Should every class? It seems to me that just the abstract class should. Of course, all of the classes could implement the interface, but that seems redundant because the children of the abstract will 'inherit' the interface because they extend the abstract class.

2) Given that the abstract class implements parts of the interface, should it also declare abstract methods for the methods it doesn't implement? It seems to me like this is right, but in a way this seems redundant because the children of the abstract will need to implement these methods in order to compile.

So what are your arguments for the best practice? The question boils down to: we've got an interface that defines what we want some classes to do, we've got a subset of the methods in the interface that define common behavior, and we've got a few different ways to define the non-common behavior. What's the best way to lay this out?

like image 272
John M Naglick Avatar asked Dec 09 '22 18:12

John M Naglick


2 Answers

The principle that should help you here id DRY: Don't Repeat Yourself (http://en.wikipedia.org/wiki/Don%27t_repeat_yourself).

In this context, DRY means that you should not do unnecessary work.

So for your 1st question the abstract class should implement the interface because it saves you from repeating the "implements X" clause at every concrete class.

As for the 2nd question, there's no point in repeating the interface methods in the abstract class that implements it. This is redundant work. Moreover when the interface evolves/changes you will need to change the counterparts (abstract) methods at the abstract class which is a headache. At some point you'll miss updating some of the method and the concrete class will need to implement these in vain.

like image 50
Itay Maman Avatar answered Jan 14 '23 05:01

Itay Maman


The abstract class should implement the interface, and provide concrete implementations of common member functions. IIRC it shouldn't need to declare abstract methods for the elements it doesn't implement, as these are assumed to be needed to be implemented by subclasses.

like image 42
James Avatar answered Jan 14 '23 07:01

James