Search code examples
javainterfaceabstract-methods

Creating new Abstract Method vs Interface Method


Q. Are you still following the principle of Program to an Interface if you are creating abstract methods in an abstract class that is not linked to an interface?

I use an Interface already for all of my UI classes that I have created; however, given the reason for the Interface, I don't see a direct correlation with the abstract method that I want to create and the already existing Interface.

Normally, I would just create the abstract method and be done; however, I am wondering if I am breaking the design principle of Program to an Interface or not.

Q. Should I create another interface for this or just stick with the abstract method?

NOTE: This is NOT an interface vs. abstract class question.

public abstract class BaseClass extends Clazz implements Interface {

    // 1 out of 4 interface methods are implemented here
    CustomObj getMode() { ... }

    // I am actually also thinking of taking that 1 method - getMode() - out of the 
    //     interface and implementing it as an implemented method without an interface. 

    // Method that made me ask this question!!
    abstract CustomObj getDefaultMode();    // Not related to the interface - Interface

}


public interface Interface {

    String getFirstNumber();
    String getSecondNumber();

    CustomObj getMode();  // This one is implemented in the BaseClass, but I think it no longer belongs in this role

    // CustomObj getDefaultMode();  // This one is not in Interface, but makes be believe I need a new Interface or just have them declared in an Abstract Class.

}

Note: My Base class is more for simplifing the code in the concrete classes. The base class deals with some overridden methods, helper methods, initialization, etc... So it is not acting like an interface, but as your standard abstract class.


Solution

  • I think the wording of the question is too abstract to give a definite yes or no answer.

    In general there's nothing wrong with abstract classes. The trouble is when people misuse them. How do we define misuse? Or rather, what's the proper use of abstract classes?

    For this we have to remember that OO is a way of modelling the "real world": good designs give easy to understand models, bad designs are hard to follow. Moreover, good OO designs can be extended in the directions the modelled problem is likely to extend too. (I'm not talking about the extends keyword here obviously.)

    What an abstract method says is this: the other methods declared in this class make no sense without this one. Whereas what an interface says is that to be an X you need at least these methods.

    So while the abstract method is a way to express demands for an implementation, an interface defines a role that anyone implementing it can play.

    Sometimes you need one, other times you need the other.