CS122/504 QUIZ 2 Prof. Lixin Tao April 18, 2006 1) What will be printed if we run the following program? [20%] class A { public A() { System.out.println("A()"); } public void finalize() { System.out.println("~A()"); } } class B extends A { public B() { System.out.println("B()"); } public void finalize() { System.out.println("~B()"); super.finalize(); } } public class ClassConstructors { public static void main(String[] args) { new B(); System.gc(); } } 2) What will be printed if we run the following program? [20%] abstract class Talkable { abstract void talk(); void sing() { System.out.println("Talker can sing."); } } class Cat extends Talkable { void talk() { System.out.println("I am a cat."); } void sing() { System.out.println("Cat can sing."); } } class Dog extends Talkable { void talk() { System.out.println("I am a dog."); } void sing() { System.out.println("Dog can sing."); } } public class TestAbstractClass { public static void main(String[] args) { Talkable[] pet = new Talkable[2]; pet[0] = new Cat(); pet[1] = new Dog(); pet[0].talk(); pet[1].talk(); pet[0].sing(); pet[1].sing(); } } 3) What will be printed if we run the following program? [20%] class Exception1 extends Exception {} class Exception2 extends Exception {} class Exception3 extends Exception {} public class ShowException { public static void main(String[] args) { for (int i = 1; i<=3; i++) { try { f(i); } catch (Exception3 e) { System.out.println("main() catched " + e); } } } static void f(int i) throws Exception3 { try { if (i == 1) throw new Exception1(); else if (i == 2) throw new Exception2(); else if (i == 3) throw new Exception3(); } catch (Exception1 e) { System.out.println("f(" + i + ") catched " + e); } catch (Exception2 e) { System.out.println("f(" + i + ") catched " + e); throw new Exception3(); } finally { System.out.println("f(" + i + ") executes finally block"); } } } 4) Design and implement a class Stack of integers with linked Node objects defined below: class Node { int value; Node next; public Node(int value, Node next) { this.value = value; this.next = next; } public Node() { this(0, null); } } [40%]