Search code examples
javainterfaceimplements

Java duplicate method when implement


I have one interface I need to use:

public interface I {  
      void go1();    
      void go2(); 
}

Then I have multiple classes that implement this

public class A implements I {
    @Override  void go1() { ... }   
    @Override  void go2() { ... } 
}

public class B implements I {
   @Override   void go1() { ... }   
   @Override   void go2() { ... } 
}

the "go2" method is identical for all classes, and duplicating it is kinda redundant

so is it better to:

1) create an abstract for all these classes and put "go2" inside?

or

2) create "go2" in each class that and call "super()"?

or

3) anything better??


Solution

  • create an abstract for all these classes and put "go2" inside?

    Yes, that's the traditional way, and may still be the only sensible way via inheritance if go2() relies on any private state. Even with Java 8 and default methods, you still can't use any private state inside an interface.

    If the method isn't reliant on private state, you may declare the method body directly in the interface by using the default keyword on the method (assuming you're using Java 8 or later.)

    If you find that neither of these approaches work brilliantly, then you could use composition instead of inheritance (using something like the decorator design pattern.)