I've read a number of threads explaining the differences between Interfaces and Abstract Classes; these posts in particular was very helpful: What is the difference between an interface and abstract class? and Interface vs Abstract Class (general OO); however, I couldn't find any answers that specifically addressed my question.
Context: Today in class we wrote an interface and two classes that implement the interface:
public interface Animal{ // This is in its own file
void move();
void makeSound();
}
class Dog implements Animal{ // The rest of these are in another file
public void move(){
System.out.println("Runs.");
}
public void makeSound(){
System.out.println("Barks.");
}
}
class Fish implements Animal{
public void move(){
System.out.println("Swims.");
}
public void makeSound(){
System.out.println("Bloops.");
}
}
public class Zookeeper{
public static void main(String[] args){
Animal[] zoo = new Animal[10]; // This an array of references to an interface
for(int i = 0; i < zoo.length; i++){
zoo[i] = (Math.round(Math.random()) == 0)?new Dog():new Fish();
}
for(Animal animal: zoo){
System.out.println(animal.getClass().getName());
animal.makeSound();
animal.move();
}
}
}
I know that it is possible because it works; my question is why does it work? I get that subclasses have an ISA relationship with their superclasses, but Interfaces aren't classes at all, so does inheritance still apply to them? Do classes that implement more than one interface have an ISA relationship to those interfaces?
The question could be further abstracted to: Why can a reference variable to an Interface house Classes that implement that interface?