CSE142 Inheritance/Polymorphism Problems handout #27 1. Assume that the following classes have been defined: public class Foo { public void method1() { System.out.println("foo 1"); } public void method2() { System.out.println("foo 2"); } public String toString() { return "foo"; } } public class Bar extends Foo { public void method2() { System.out.println("bar 2"); } } public class Baz extends Foo { public void method1() { System.out.println("baz 1"); } public String toString() { return "baz"; } } public class Mumble extends Baz { public void method2() { System.out.println("mumble 2"); } } Consider the following code fragment: Foo[] elements = {new Foo(), new Bar(), new Baz(), new Mumble()}; for (int i = 0; i < elements.length; i++) { System.out.println(elements[i]); elements[i].method1(); elements[i].method2(); System.out.println(); } What output is produced by this code? 2. Assume the following classes have been defined: public class Foo extends Blue { public void method2() { System.out.println("foo 2"); } public String toString() { return "foo"; } } public class Blue extends Moo { public void method1() { System.out.println("blue 1"); } } public class Shoe extends Foo { public void method1() { System.out.println("shoe 1"); } } public class Moo { public void method1() { System.out.println("moo 1"); } public void method2() { System.out.println("moo 2"); } public String toString() { return "moo"; } } Consider the following code fragment: Moo[] elements = {new Shoe(), new Foo(), new Moo(), new Blue()}; for (int i = 0; i < elements.length; i++) { System.out.println(elements[i]); elements[i].method1(); elements[i].method2(); System.out.println(); } What output is produced by this code?
Solution to CSE142 Inheritance/Polymorphism Problems 1. The program produces the following output: foo foo 1 foo 2 foo foo 1 bar 2 baz baz 1 foo 2 baz baz 1 mumble 2 2. The program produces the following output: foo shoe 1 foo 2 foo blue 1 foo 2 moo moo 1 moo 2 moo blue 1 moo 2
Stuart Reges
Last modified: Fri Dec 2 16:27:59 PST 2005