Java Reference
In-Depth Information
The type of a variable declares what it can store. Declaring a variable of type Vehicle states
that this variable can hold vehicles. But because a car is a vehicle, it is perfectly legal to store
a car in a variable that is intended for vehicles. (Think of the variable as a garage: if someone
tells you that you may park a vehicle in a garage, you would think that parking either a car or a
bicycle in the garage would be okay.)
Subtype objects
may be used
wherever objects
of a supertype
are expected.
This is known as
This principle is known as substitution. In object-oriented languages, we can substitute a sub-
class object where a superclass object is expected, because the subclass object is a special case
of the superclass. If, for example, someone asks us to give them a pen, we can fulfill the request
perfectly well by giving them a fountain pen or a ballpoint pen. Both fountain pen and ballpoint
pen are subclasses of pen, so supplying either where an object of class Pen was expected is fine.
However, doing it the other way is not allowed:
Car c1 = new Vehicle(); // this is an error!
This statement attempts to store a Vehicle object in a Car variable. Java will not allow this,
and an error will be reported if you try to compile this statement. The variable is declared to
be able to store cars. A vehicle, on the other hand, may or may not be a car—we do not know.
Thus, the statement may be wrong and is not allowed.
Car c2 = new Bicycle(); // this is an error!
This is also an illegal statement. A bicycle is not a car (or, more formally, the type Bicycle is
not a subtype of Car ), and thus the assignment is not allowed.
Exercise 8.12 Assume that we have four classes: Person , Teacher , Student , and
PhDStudent . Teacher and Student are both subclasses of Person . PhDStudent is a
subclass of Student .
a. Which of the following assignments are legal, and why or why not?
Person p1 = new Student();
Person p2 = new PhDStudent();
PhDStudent phd1 = new Student();
Teacher t1 = new Person();
Student s1 = new PhDStudent();
b. Suppose that we have the following legal declarations and assignments:
Person p1 = new Person();
Person p2 = new Person();
PhDStudent phd1 = new PhDStudent();
Teacher t1 = new Teacher();
Student s1 = new Student();
Based on those just mentioned, which of the following assignments are legal, and why or why not?
s1 = p1;
s1 = p2;
p1 = s1;
Search WWH ::

Custom Search