Workshop
本页目录· 2 条
2.1 Polymorphism: Activities
Task 1
Suppose you have four classes: Animal, Dog, Cat, and Beagle. Dog and Cat are both subclasses of Animal. Beagle is a subclass of Dog.
(a) Which of the following assignments are legal, and why or why not?
Animal a1 = new Dog();
Animal a2 = new Beagle();
Beagle b1 = new Dog();
Cat c1 = new Animal();
Dog d1 = new Beagle();(b) Suppose that we have the following declarations and assignments:
SaladItem s1 = new SaladItem();
SaladItem s2 = new SaladItem();
IcebergLettuce i1 = new IcebergLettuce();
Tomato t1 = new Tomato();
Lettuce l1 = new Lettuce();Based on the class names used, decide on a sensible inheritance hierarchy for the classes in the above code. Using your inheritance hierarchy, which of the following assignments would be legal, and why or why not?
l1 = s1;
l1 = s2;
s1 = l1;
t1 = l1;
l1 = i1;
i1 = l1;Task 2
Test your answers to the previous question by creating barebones versions of the classes mentioned in that exercise.
Task 3
Look at the code below. You have four classes: A, B, C, and D; and you have a variable assigned to each class type, as follows:
A a;
B b;
C c;
D d;The following assignments are all legal (assume that they all compile):
d = c;
d = b;
a = c;The following assignments are all illegal (they cause compiler errors):
a = d;
a = b;
b = a;What can you say about the relationships of these classes? Draw a class diagram.
Answer
Task 1
Animal, Dog, Cat, and Beagle. Dog and Cat are both subclasses of Animal. Beagle is a subclass of Dog.
(a)
Animal a1 = new Dog(); - legal
Animal a2 = new Beagle(); - legal
Beagle b1 = new Dog(); - not leagal
Cat c1 = new Animal(); - not leagal
Dog d1 = new Beagle(); - legal
(b)
SaladItem s1 = new SaladItem();
SaladItem s2 = new SaladItem();
IcebergLettuce i1 = new IcebergLettuce();
Tomato t1 = new Tomato();
Lettuce l1 = new Lettuce();
Based on the class names used, decide on a sensible inheritance hierarchy for the classes in the above code. Using your inheritance hierarchy, which of the following assignments would be legal, and why or why not?
SaladItem
- Tomato
- Lettuce
- IcebergLettuce
l1 = s1; - not legal
l1 = s2; - not legal
s1 = l1; - legal
t1 = l1; - not legal
l1 = i1; - legal
i1 = l1; - not legal
Task 2
// Superclass
public class SaladItem {
}
// Subclass of SaladItem
public class Lettuce extends SaladItem {
}
// Subclass of Lettuce
public class IcebergLettuce extends Lettuce {
}
// Subclass of SaladItem
public class Tomato extends SaladItem {
}
---
public class SaladTest {
public static void main(String[] args) {
SaladItem s1 = new SaladItem();
SaladItem s2 = new SaladItem();
IcebergLettuce i1 = new IcebergLettuce();
Tomato t1 = new Tomato();
Lettuce l1 = new Lettuce();
}
}
---
Task 3
D is a superclass of B and C
A is an interface implemented by C