Lamp
Category: Polymorphism
Author: Stuart Reges
Book Chapter: 9.3
Problem: Lamp
Assume the following classes have been defined:
public class Pen extends Sock {
public void method1() {
System.out.println("pen 1");
}
}
public class Lamp {
public void method1() {
System.out.println("lamp 1");
}
public void method2() {
System.out.println("lamp 2");
}
public String toString() {
return "lamp";
}
}
public class Book extends Sock {
public void method2() {
System.out.println("book 2");
}
}
public class Sock extends Lamp {
public void method1() {
System.out.println("sock 1");
}
public String toString() {
return "sock";
}
}
Consider the following code fragment:
Lamp[] elements = {new Book(), new Pen(), new Lamp(), new Sock()};
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?