3

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??

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Maaz Soan
  • 113
  • 2
  • 8

2 Answers2

4

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.)

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
3

one solution would be to make go2() a default method:

public interface I { 
    void go1(); 
    default void go2() { /* do logic*/}
}

therefore you can encapsulate the common logic for the go2 method within the interface and have all subclasses inherit that behavior.

However, it's important to note that default methods can be implemented only in the terms of calls to other interface methods. Therefore, if the method relies on private state then you'll need to create an abstract class and define the behavior there as you've mentioned and have subclasses call it when required.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • I have a "could not resolve variable" issue when i run this – Maaz Soan Dec 31 '17 at 20:08
  • not exactly sure where your error is coming from as the quote you've specified is not specific enough but please read the last paragraph as it's important. – Ousmane D. Dec 31 '17 at 20:22
  • go2 process data from go1 which uses variables and modify them if needed – Maaz Soan Dec 31 '17 at 20:34
  • What kind of variables? Show the code please. Note, indeed you have only access to the variables scoped in the method go2() and constants of the interface. There are no object variables here, it'S an interface. – UninformedUser Jan 01 '18 at 04:20