Domanda

I have 2 different methods that needs to be repeated across my program, e.g. methodA, and methodB.

Some part of the program needs to call methodA, and some others need to call methodB, and some needs to call them both. The implementation of these methods are the same across the program.

How should I structure the classes and methods to reduce the repetition? First thing that came to my mind was that I wish Java supports multiple inheritance.

The second thing that I thought of was to put each of the methods in their own interface, and have the classes implement them as necessary, but the implementation of the methods are exactly the same across the program, so having to define the implementation in each class doesn't sounds like a good idea.

I am limited to Java 6. 7 if I can convince the others in my team, so the default methods implementation coming with Java 8 is not an option.

p.s. I realize the title of the question is a very bad one, but I can't think of an easy way to explain this problem. Please suggest better one if you have any.

È stato utile?

Soluzione

Off the top of my head:

public interface Foo{  
  public Object processA(Object first);
  public Object processB(Ojbect second);
}

public abstract class AbstractFoo implements Foo{
   protected AbstractFoo(){}

   public Object processA(Object o){
       // do stuff
       return null;
   }

   public Object processB(Object o){
       // do more stuff
       return null;
   }
 }

 public class ConcreteFoo extends AbstractFoo {
 }

Altri suggerimenti

If this is a part of refactoring your code, why can't you put your repeating code in a side(maybe private) methodC and call it from those both methods?

You should have 2 interfaces, but you can have one class implementing both interfaces.

That's depend on what type of program you are writing.If it is a web system,I think you should bulid these two,because layer is necessary.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top