Interfaces can be extremely helpful in many cases. For example, say you had a list of animals and you wanted to loop through the list, each printing the sound they make.
{cat, dog, bird}
One way to do this would be to use interfaces. This would allow for the same method to be called on all of the classes
public interface Animal {
public String getSound();
}
Any class that implements Animal
also must have a getSound()
method in them, yet they can all have different implementations
public class Dog implements Animal {
public String getSound() {
return "Woof";
}
}
public class Cat implements Animal {
public String getSound() {
return "Meow";
}
}
public class Bird implements Animal{
public String getSound() {
return "Chirp";
}
}
We now have three different classes, each of which has a getSound()
method. Because all of these classes implement
the Animal
interface, which declares the getSound()
method, any instance of an Animal
can have getSound()
called on it
Animal dog = new Dog();
Animal cat = new Cat();
Animal bird = new Bird();
dog.getSound(); // "Woof"
cat.getSound(); // "Meow"
bird.getSound(); // "Chirp"
Because each of these is an Animal
, we could even put the animals in a list, loop through them, and print out their sounds
Animal[] animals = { new Dog(), new Cat(), new Bird() };
for (Animal animal : animals) {
System.out.println(animal.getSound());
}
Because the order of the array is Dog
, Cat
, and then Bird
, "Woof Meow Chirp" will be printed to the console.
Interfaces can also be used as the return value for functions. For example, returning a Dog
if the input is "dog", Cat
if the input is "cat", and Bird
if it is "bird", and then printing the sound of that animal could be done using
public Animal getAnimalByName(String name) {
switch(name.toLowerCase()) {
case "dog":
return new Dog();
case "cat":
return new Cat();
case "bird":
return new Bird();
default:
return null;
}
}
public String getAnimalSoundByName(String name){
Animal animal = getAnimalByName(name);
if (animal == null) {
return null;
} else {
return animal.getSound();
}
}
String dogSound = getAnimalSoundByName("dog"); // "Woof"
String catSound = getAnimalSoundByName("cat"); // "Meow"
String birdSound = getAnimalSoundByName("bird"); // "Chirp"
String lightbulbSound = getAnimalSoundByName("lightbulb"); // null
Interfaces are also useful for extensibility, because if you want to add a new type of Animal
, you wouldn't need to change anything with the operations you perform on them.