Exercise 8.11
Which of the following assignments are legal, and why?
a) Person p1 = new Student();
- This is legal because Student is a subclass of Person.
b) Person p2 = new PhDStudent();
- This is legal because PhDStudent is a subclass of Person (because it is a subclass of Student which is a subclass of Person)
c) PhDStudent phd1 = new Student();
- This is not legal, because a student is not a subclass of PhDStudent.
d) Teacher t1 = new Person();
- This is not legal because a Person is not a subclass of Teacher.
e) Student s1 = new PhDStudent;
- This is legal, because PhDStudent is a subclass of Student.
Assume that the two illegal lines above are changed to:
PhDStudent phd1;// = new Student(); Teacher t1;// = new Person();
f) s1 = p1
- This is not legal, because a Person is not a subclass of Student. The compiler only knows the static type of p1 which is Person - it does not know the dynamic type which is Student.
g) s1 = p2
- This is not legal, because a Person is not a subclass of Student (same arguments as in f).
h) p1 = s1
- This is legal because Student is a subclass of Person.
i) t1 = s1
- This is not legal because Student is not a subclass of Teacher.
j) s1 = phd1
- This is legal because PhDStudent is a subclass of student.
k) phd1 = s1
- This is not legal because Student is not a subclass of PhDStudent.
|