Computer Science 15-100 (Sections T & U), Fall 2007
Class Notes: (Inheritance and) Polymorphism
Logistics
Code from class:
class Foo {
public static void main(String[] args) {
Demo.ex2();
}
}
// abstract class Animal { // make Animal abstract so you cannot instantiate class Animal {
protected int legs = 2;
public void speak() { System.out.println("animal-sound"); }
// abstract public void speak();
public void printLegs() { System.out.println("Legs = " + this.legs); } }
class Dog extends Animal {
// protected int legs = 4; // shadowed variable -- bad idea
public Dog() { this.legs = 4; }
public void speak() { System.out.println("au"); }
// public void printLegs() { System.out.println("Dog Legs = " + this.legs); } }
class Cat extends Animal {
protected int legs = 4;
public Cat(int lives) { this.lives = lives; }
public void speak() { System.out.println("meow (" + this.lives + ")"); }
private int lives;
}
class ConfusedCat extends Cat {
public ConfusedCat() { super(3); }
public void speak() {
super.speak();
System.out.println("?");
}
}
class Demo {
public static void ex2() {
// demonstrate polymorphism using Animal, Dog, and Cat
Animal a;
a = new Animal();
a.speak();
a.printLegs();
a = new Dog();
a.speak();
a.printLegs();
a = new Cat(5);
a.speak();
a = new ConfusedCat();
a.speak();
}
public static void ex1() {
// demonstrate polymorphism using Number and Double and Integer
Number n;
n = 3.14;
// demo autoboxing (again)
System.out.println(n instanceof Float);
System.out.println(n instanceof Double);
System.out.println(n instanceof Number);
System.out.println(n.getClass().getName());
Double d = new Double(2.8);
n = d;
System.out.println(n.intValue()); // polymorphism in action! #1 of 2
System.out.println(n.doubleValue());
System.out.println(d.isInfinite());
// System.out.println(n.isInfinite()); // WILL NOT COMPILE
System.out.println(((Double)n).isInfinite());
n = new Integer(3);
System.out.println(n.intValue()); // polymorphism in action! #2 of 2
System.out.println(n.doubleValue());
System.out.println(((Double)n).isInfinite());
}
}
Carpe diem!