import java.util.*; abstract class Worker { public Worker() { hunger = 0; allWorkers.addElement(this); } public void work () { hunger++; workDone++; System.out.println("whistle"); } public void eat () { hunger--; System.out.println("yum"); } public void live() { work(); eat(); } abstract public void printWorksWith(); // Prints the names of people one // works with; depends on kind of worker. public String toString() { return "hunger level is: " + hunger; } public static void showWorkForce() { int i = 0; System.out.println("All the workers in the world:"); for (i = 0; i < allWorkers.size(); i++) { System.out.println(" " + allWorkers.elementAt(i)); } } protected int hunger; private static int workDone = 0; private static Vector allWorkers = new Vector(); } class TA extends Worker { public TA(String p) { super(); prof = p; classList = new Vector(); } public void workAlternate() { // used in lecture 11 as the "work" method super.work(); /* do whatever a Worker does to work */ System.out.println("let me help"); } public void work() { hunger++; System.out.println("let me help"); } public void printWorksWith() { System.out.println("Professor of course: " + prof); System.out.println("Students in section: " + classList); } public String toString() { return super.toString() + ", class size: " + classList.size(); } public void add(String student) { classList.addElement(student); } private String prof; private Vector classList; } class Lecture12 { static void foo (Worker w) { System.out.println("A week in a worker's life."); for (int i = 0; i < 5; i++) { w.live(); } w.eat(); w.eat(); // t.add("Jeff"); not } static void bar (TA t) { t.live(); t.add("Jeff"); } public static void main(String[] argv) { /* If Worker is not abstract, the following works. System.out.println("\nWorker w1 lives."); Worker w1 = new Worker(); w1.live(); foo(w1); // bar(w1); not legal, even if Worker is not abstract */ System.out.println("\nTA t1 lives."); TA t1 = new TA("Yelick"); t1.live(); foo(t1); bar(t1); t1.printWorksWith(); Worker.showWorkForce(); System.out.println("\n"); // test interfaces (below) IntBox ib1 = new IntBox(2); IntBox ib2 = new IntBox(3); System.out.println("ib1.lessThan(ib2) is: " + ib1.lessThan(ib2)); ib2.negate(); System.out.println("...after negating ib2"); System.out.println("ib1.lessThan(ib2) is: " + ib1.lessThan(ib2)); } } /* * * * * * * * * * * * Interfaces * * * * * * * * * * * * * * */ interface Negatable { void negate(); } interface Comparable { boolean lessThan (Comparable c); boolean greaterThan (Comparable c); } class IntBox implements Negatable, Comparable { public IntBox(int v) { value = v; } public int getValue() { return value; } public void setValue(int v) { value = v; } public void negate() { value = -value; } public boolean lessThan (Comparable c) { return value < ((IntBox) c).value; } public boolean greaterThan (Comparable c) { return value > ((IntBox) c).value; } private int value; }