Why is this better than just having individual methods in your classes, and not implementing an interface?
Because if a class C
implements an interface I
, you can use a C
whenever an I
is expected. If you do not implement the interface, you could not do this (even if you provided all of the appropriate methods as mandated by the interface):
interface I {
void foo();
}
class C1 implements I {
public void foo() {
System.out.println("C1");
}
}
class C2 { // C2 has a 'foo' method, but does not implement I
public void foo() {
System.out.println("C2");
}
}
...
class Test {
public static void main(String[] args) {
I eye1 = new C1(); // works
I eye2 = new C2(); // error!
}
}