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


Logistics

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

Code from class:

import java.util.ArrayList;

@SuppressWarnings("unchecked")
class MyCode {
    public static void main(String[] args) {
      ArrayList al = new ArrayList();
      MutableString s = new MutableString("foo");
      
      al.add(s);
      s = new MutableIntString(1,2);
      System.out.println(s.toString());
      al.add(s);
      System.out.println(al);
      s.set("bar");
      System.out.println(al); // see bar here
    }
}

class MutableIntString extends MutableString {
  public MutableIntString(int i, int j) { super("" + Math.min(i,j)); }
  
  public String toString() { return "MIS:" + super.toString(); } }

class MutableString {
  
  public MutableString(String s) { this.s = s; }
  
  public String get() { return this.s; }
  
  public void set(String s) { this.s = s; }
  
  public String toString() { return this.s; }
  
  private String s;
}

class A {
    public void foo() {
        System.out.print("a");
        System.out.print((this instanceof C) ? "t" : "f");
    }
}

class B extends A {
    public void foo() {
        System.out.print("b");
    }
}

class C extends A {
    public void foo() {
        super.foo();
        System.out.print("c");
    }
}

class D extends C {
    public void foo() {
        System.out.print("d");
        super.foo();
        super.foo();
    }
}

Carpe diem!