1

Pls find the link for reference: "Strategy for success" article of JavaWorld

My question is why do we need to have separate interface and implement it in abstract class, when we can declare those abstract methods in abstract class itself?

ex in image,

public interface Border(){
      paintBorder();
      getBorderInsets();
      isBorderOpaque();
 }


public class abstract AbstractBorder implements Border(){
 .....
}

instead we can have abstract class like

public class abstract AbstractBorder {
      paintBorder();
      getBorderInsets();
      isBorderOpaque();
 }

why we are using interface? what is the necessity?

MayogaX
  • 469
  • 3
  • 18
  • Possible duplicate of [Interface vs Abstract Class (general OO)](http://stackoverflow.com/questions/761194/interface-vs-abstract-class-general-oo) – Ravindra babu Jun 07 '16 at 07:34

3 Answers3

1

Maybe the interface defines behavior that might be present in other abstract classes, other than the one you mentioned. One good example of this is the IDisposable interface.

If you decide to declare these methods inside the abstract class itself, you might end up having to deal with a lot of clutter when you implement a concrete class from this abstract one. Also, since you can specify behavior inside an abstract class, this behavior might be reused by the implementing classes.

viniciushana
  • 235
  • 1
  • 2
  • 12
0

This is something I had thought about too when I had started with Java. A very detailed answer can be found here. Do comment if you need any further clarification.

Roney Michael
  • 3,964
  • 5
  • 30
  • 45
0

Is a good pratice programming to interface, and not to class. In the Strategy Pattern the idea is have interfaces of "strategies" and in the run time you can to change the strategy (the class that implement the interface) without to change without changing much of the rest of your code.

This is a good start to the SOLIDprinciples making your code more flexible and stronger.

I have a exemple of the Strategy Pattern in my github and in the object "Cavaleiro" (Knight in English) is changed in run time.

For that I create a interface and used it and not a object of a class, and by it I can change the "strategy" easy.

MayogaX
  • 469
  • 3
  • 18