Sample Code
Last updated on: Sunday January 21st 2001
/*
C. Jones, Winter 2001
Very simple example of polymorphism - declared type of anAnimal is Animal, but
anAnimal can be bound to an instance of its subclass, Dog.
Also, the displayMe() method is overridden in the subclass.
Note: which version of displayMe() is invoked after anAnimal
has been bound to an instance of the Dog class?
*/
public class Example2 {
public static void main(String args[]) {
Animal anAnimal = new Animal();
anAnimal.displayMe();
anAnimal = new Dog();
anAnimal.displayMe();
}
}
public class Animal {
protected String name;
protected int legs;
public Animal(){
this.name = "Animal";
this.legs = 0;
}
public Animal(String name, int legs){
this.name = name;
this.legs = legs;
}
public void displayMe(){
// print my details on screen
System.out.println(this.name + ", " + this.legs);
}
}
public class Dog extends Animal {
private static String noise = "Woof!";
public Dog(){
super("Dog", 4);
}
public void displayMe(){
// print my details on screen
System.out.println(this.name + ", " + this.legs + ", " + Dog.noise);
}
}
| |
||