Today in class we have just seen the first examples of class, object and interfaces; however, the usefulness of the latter is not clear to me. for example, given the following code:
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
It is not clear to me why we should use an interface if we are to implement the same methods in the class. Can't we write them directly into the class?
The example code was taken from w3schools.