class Animal { protected String breed; public Animal(String breed) { this.breed = breed; } public String getBreed() { return breed; } public void talk() { System.out.print(""); } }
class Cow extends Animal { public Cow() { super("cows"); } public void talk() { System.out.print("Moo"); } }
class Pig extends Animal { public Pig() { super("pigs"); } public void talk() { System.out.print("Oink"); } }
class Aardvark extends Animal { public Aardvark() { super("aardvarks"); } public void talk() { System.out.print("Snaffle"); } }
Animal
Animal a1; Animal a2;
Animal
object and assign it to
one of the variables:
a1 = new Animal("mute swans");
Cow
and assign it to one
of the variables:
a2 = new Cow();
int
into a double
Publication p = new ConferencePaper(....);
Animal a = new Cow(); a.talk();Which version of
talk
is run?
Cow
, so it is talk
in Cow
that is executed
private
, static
or final
)
Animal a = new Cow(); a.talk(); a = new Pig(); a.talk(); System.out.println(a.getBreed()); a = new Animal("Centipede"); a.talk(); System.out.println(a.getBreed());
Although variable a
is of type Animal
,
Java didn't repeatedly execute methods in Animal
.
During the program, a
references various different
classes of object and the method that was executed depended on
what a
was referencing
In the following, livestock
is a polymorphic data
structure: it can hold objects of different forms –
objects that are any subclass of Animal
public class SingAlong { public static void main(String[] args) { Animal[] livestock = new Animal[3]; livestock[0] = new Cow(); livestock[1] = new Pig(); livestock[2] = new Aardvark(); for (int i = 0; i < livestock.length; i = i + 1) { System.out.print("Old MacDonald had a farm. "); System.out.println("Eee Eye, Eee Eye, Oh!"); System.out.print("And on that farm he had some "); System.out.print(livestock[i].getBreed() + ". "); System.out.println("Eee Eye, Eee Eye, Oh!"); for (int j = i; j >= 0; j = j - 1) { Animal a = livestock[j]; System.out.print("With a '"); a.talk(); a.talk(); System.out.print("' here, and a '"); a.talk(); a.talk(); System.out.println("' there."); System.out.print("Here a '"): a.talk(); System.out.print("', there a '"); a.talk(); System.out.println("'."); System.out.println("Everywhere a '"); a.talk(); a.talk(); System.out.println("'."); } System.out.print("Old MacDonald had a farm. "); System.out.println("Eee Eye, Eee Eye, Oh!"); System.out.println(); } } }
if
in sight!Animal
is easy;
and there's no if
to extend with another
case – so nothing really changes
Animal
should be an abstract class
and talk
in Animal
should be an
abstract method – see next lecture
class Animal { private String breed; private String noise; public Animal(String breed, String noise) { this.breed = breed; this.noise = noise; } public String getBreed() { return breed; } public void talk() { System.out.print(noise); } }