Computer Science 15-100 (Sections T & U), Fall 2007
Class Notes:   (Inheritance and) Polymorphism


Logistics

  1. Reading:  L&L Chapter 9... (except 8.6)

  1. More on Inheritance...
    1. Class Hierarchies
    2. Read Section 8.5 (of course, read the others, too!):  Designing for Inheritance
    3. Visibility and Subclasses (public, default/package, protected, private)
    4. Bad Idea #1374:  Shadowing instance variables with subclass instance variables
    5. final variables, methods, and classes
    6. Time permitting:
      1. Implementing a MouseListener
      2. Extending a MouseAdapter
      3. Using a Timer
  2. Polymorphism

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!