0

Let's say I have a class A and class B and both the classes needs to have common methods. Let's consider below scenario.

class A{

    void commonMethod1(){...};
    void commonMethod2(){...};
    
    void someStuff();
   
     }

class B{

    void commonMethod1(){...};
    void commonMethod2(){...};
    
    void someOtherStuff();
   
     }

In the above example , both A and B classes have 2 common methods which has same functionality. Now I would like to know whether to create a new class called Utility and include those common methods and let A and B classes extend Utility class?

Or create a interface SomeInterface and have 2 common methods as default methods with implementation and let class A and B implement the interface? which is the better design?

I feel implementing interface is preferred than extending a class ( so class A and class B can still extend some xyz class in future if I go for interface now) . What are your thoughts?

Stunner
  • 961
  • 2
  • 19
  • 39
  • Does this answer your question? [When to use: Java 8+ interface default method, vs. abstract method](https://stackoverflow.com/questions/19998454/when-to-use-java-8-interface-default-method-vs-abstract-method) – Robert Harvey Nov 26 '20 at 04:02
  • It's pretty much six of one, half dozen of the other. It depends on if you need to use instance variables or not. – NomadMaker Nov 26 '20 at 04:02
  • @Robert I just read that link before posting this question .. It din't answer my question. Abstract method is nowhere in my scenario – Stunner Nov 26 '20 at 04:02
  • @NomadMaker Design wise , which one is better? can we make use of default methods here in this case? Is it right scenario to use default methods in this case?\ – Stunner Nov 26 '20 at 04:04
  • How about both? Use an interface, and then an abstract class that implements the interface? – NomadMaker Nov 26 '20 at 04:06
  • Why abstract class? Any reason? – Stunner Nov 26 '20 at 04:06

0 Answers0