Animal
interface requires getName
and
getSound
methods.
public interface Animal {
public String getName();
public String getSound();
}
The ArrayList allows objects of any class that implements Animal
interface. Because all such classes must have getName
and
getSound
methods, we can call these methods on any
Animal object.
import java.util.ArrayList;
public class OldMac {
public static void main(String [] args) {
ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Duck());
animals.add(new Cow());
animals.add(new Pig());
for (Animal animal: animals) {
printVerse(animal);
}
}
public static void printVerse(Animal theAnimal) {
String name = theAnimal.getName();
String sound = theAnimal.getSound();
String verse = "Old MacDonald had a farm, \n" +
"E-I-E-I-O\n" +
"And on his farm he had a " + name + ",\n" +
"E-I-E-I-O\n" +
"With a " + sound + ", " + sound + " here,\n" +
"And a " + sound + ", " + sound + " there,\n" +
"Here a " + sound + ", there a " + sound +",\n" +
"Everywhere a " + sound + ", " + sound + ",\n" +
"Old Mac Donald had a farm,\n" +
"E-I-E-I-O";
System.out.println(verse + "\n");
}
}
Classes that implement the interface:
// since Duck is an Animal, it must have
// all methods declared in the Animal interface
public class Duck implements Animal {
// default constructor (no parameters)
// don't have to write it, but can if we want
public Duck() {
}
public String getName() {
return "duck";
}
public String getSound() {
return "quack";
}
}
public class Cow implements Animal {
// skipping the default constructor
public String getName() {
return "cow";
}
public String getSound() {
return "moo";
}
}
public class Pig implements Animal {
// skipping the default constructor
public String getName() {
return "pig";
}
public String getSound() {
return "oink";
}
}