CSE142 Inheritance/Polymorphism Problems handout #18
1. Assume that the following classes have been defined:
public class Foo {
public String toString() {
return "foo";
}
public void method1() {
System.out.println("foo 1");
}
public void method2() {
System.out.println("foo 2");
}
}
public class Bar extends Foo {
public void method2() {
System.out.println("bar 2");
}
}
public class Baz extends Foo {
public String toString() {
return "baz";
}
public void method1() {
System.out.println("baz 1");
}
}
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? (write the output as a series of 3-line
columns in order from left to right)
2. Assume the following classes have been defined:
public class Foo extends Blue {
public String toString() {
return "foo";
}
public void method2() {
System.out.println("foo 2");
}
}
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 String toString() {
return "moo";
}
public void method1() {
System.out.println("moo 1");
}
public void method2() {
System.out.println("moo 2");
}
}
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? (write the output as a series of 3-line
columns in order from left to right)
Solution to CSE142 Inheritance/Polymorphism Problems
1. The program produces the following output:
foo foo baz baz
foo 1 foo 1 baz 1 baz 1
foo 2 bar 2 foo 2 mumble 2
2. The program produces the following output:
foo foo moo moo
shoe 1 blue 1 moo 1 blue 1
foo 2 foo 2 moo 2 moo 2