I've looked up the "interface" function several places, but nowhere does it seem to actually explain the benefits of using it, or why I should use interfaces when writing my own future programs.
I finished the exercise below, where I used an interface named "Form" to describe the methods "circumference" and "area". Then I have 3 classes "Circle", "Rectangle" and "Square" where the variables from each form are input and calculated to finally retrieve the circumference and area of each form.
My problem is that after I finished the exercise, I'm struggling to really see the point of implementing this "Form" interface. I feel like I could have just ignored using an interface and then simply through inheritance, make each of the classes inherit the circumference and area methods and then just create objects for each of the forms at the end when compiling?
How did the interface make things easier for me?
public class FormCompiling {
public static void main(String[] args) {
Form[] f = {new Circle(1.5), new Rectangle(2.0,3.0), new Square(2.5)};
System.out.println("Area:");
for(int i = 0 ; i<f.length; i++) {
System.out.println(f[i].area());
}
}
}
public interface Form {
public double circumference();
public double area();
}
public class Circle implements Form {
double radius = 0;
double area = 0;
double circumference = 0;
Circle(double radius) {
this.radius = radius;
}
@Override
public double circumference() {
circumference = 2 * radius * Math.PI;
return circumference;
}
@Override
public double area() {
area = radius * radius * Math.PI;
return area;
}
}
public class Rectangle implements Form {
double length = 0;
double width = 0;
double area = 0;
double circumference = 0;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double circumference() {
circumference = (2 * length) + (2 * width);
return circumference;
}
@Override
public double area() {
area = length * width;
return area;
}
}
public class Square extends Rectangle implements Form {
Square(double length) {
super(length, length);
this.length = length;
}
@Override
public double circumference() {
circumference = 4 * length;
return circumference;
}
@Override
public double area() {
area = length * length;
return area;
}
}