Sometimes, the actual class of an instance does not matter, but only the interface it implements.
Also sometimes, it is impossible to know the actual class of an instance in compile time, but we only know the interface this class will implement.
For example, you have an interface called GeometricFigure
public static interface GeometricFigure {
public Double getGirth();
public String getName();
}
And you use this interface in a real class, for example, Canvas
. Canvas
has a list of GeometricFigure
s.
public class Canvas {
private List<GeometricFigure> figures;
public void printAllFigures() {
for (GeometricFigure figure : figures) {
System.out.println(figure.getName() + " " + figure.getGirth());
}
}
}
Now, your Canvas
is independent of actual implementations of GeometricFigure
. Canvas
does not care how you is GeometricFigure
is implemented, is it a square, circle or whatever. It only that this class can return a name and a girth so it can print them. So, the actual implementations can be Square
, Circle
, Triangle
, etc. Only important thing is that these future classes implement the GemometricFigure
interface.
For example:
public class Square implements GeometricFigure {
private String name;
private Double sideLength;
public Square(String name, Double sideLength) {
this.name = name;
this.sideLength = sideLength;
}
@Override
public Double getGirth() {
return 4 * sideLength;
}
@Override
public String getName() {
return name;
}
}