Home » Java » oop – What is the advantage/point of using Interfaces in Java?-Exceptionshub

oop – What is the advantage/point of using Interfaces in Java?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m very new into Java and I’ve reached the chapter in my textbook that talks about interfaces. However, I am failing to see their use/point. I’m sure that they’re not useless though and that it’s just me not understanding the subject.

So, interfaces are like abstract classes and they only name methods, not their implementations. The first example provided in the book talks about having a class Shape, an extended class rectangle and the idea is to allow for a method to stretch the rectangle by its biggest side. So the code starts:

public interface Stretchable {
    void stretch( double factor );
{

Then they describe the “point” of using it

public class Rectangle extends Shape implements Stretchable
{
   public void stretch( double factor )
   {
      if( factor <0 )
      throw new IllegalArgumentException();

      if( length > width )
          length *= factor;
      else
          width*= factor;
   }
}

However, I fail to see what did I win there, by defining and implementing an interface. the interface was just void stretch( double factor); and I still had to define the same thing in the Rectangle class. What is the advantage in doing this, when I still have to define from scratch what the method of the interface is going to do in the class it’s being implemented on?

How to&Answers:

Because you define a common behavior for all classes, that can be stretched (Stretchable). Say you have a Circle:

public class Circle extends Shape implements Stretchable
{
   public void stretch( double factor )
   {
      this.radius = this.radius * factor;
   }
}

Now if you can have a collection of all the things, that can be stretched, because there is a common interface:

List<Stretchable> stretchables = List.of(new Circle(1), new Rectangle(1, 2));

Since they are all Stretchable, you can invoke the method on all of the objects:

stretchables.forEach(stretchable -> stretchable.stretch(2));