1

I know this type question has been answered multiple times and it might get tagged as duplicate

I have a structure like this

public interface service{

    public void sayHello();
}

public abstract class AbstractService{

    public void sayHello(){
        System.out.println("Hello!!");
    }
}

public class MyService extends AbstractService implements service{

    public void sayHello(){
        super.sayHello();
    }
}

I know java does not allow multiple inheritance and we use interfaces to get away with that. But with this structure, I can't find a benefit/a business case on why I need to extend and implement? Because I have a concrete method in my abstract class.

GMachado
  • 791
  • 10
  • 24
bajji
  • 1,271
  • 3
  • 15
  • 37

1 Answers1

1

Think of a case where you have many, lets's say 10 w.l.g, extensions of the AbstractService and most of them (if not all) have the same behaviour in the method sayHello. You would need to implement this method in each class that implements the interface and you'll end up having a lot of duplcated code. This approach, in Java 7 or older, saves you in such cases.

Why did I say Java 7 or older? Well, since Java 8, interfaces have default methods implementation where you can actually provide a default implementation of the method, which you can override when you need to.

NiVeR
  • 9,644
  • 4
  • 30
  • 35