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?