Java Reference
In-Depth Information
In our new version, we have a single method to serve the same purpose:
public void addPost(Post post)
Subtype As an
analog to the
class hierarchy,
types form a type
hierarchy. The type
defined by a sub-
class definition is a
subtype of the type
of its superclass.
The parameters in the original version are defined with the types MessagePost and
PhotoPost , ensuring that we pass MessagePost and PhotoPost objects to these methods,
because actual parameter types must match the formal parameter types. So far, we have in-
terpreted the requirement that parameter types must match as meaning “must be of the same
type”—for instance, that the type name of an actual parameter must be the same as the type
name of the corresponding formal parameter. This is only part of the truth, in fact, because an
object of a subclass can be used wherever its superclass type is required.
Subclasses and subtypes
We have discussed earlier that classes define types. The type of an object that was created
from class MessagePost is MessagePost . We also just discussed that classes may have
subclasses. Thus, the types defined by the classes can have subtypes. In our example, the type
MessagePost is a subtype of type Post .
Subtyping and assignment
When we want to assign an object to a variable, the type of the object must match the type of
the variable. For example,
Variables and
subtypes Variables
may hold objects of
their declared type
or of any subtype
of their declared
Car myCar = new Car();
is a valid assignment, because an object of type Car is assigned to a variable declared to hold
objects of type Car . Now that we know about inheritance, we must state the typing rule more
completely: a variable can hold objects of its declared type or of any subtype of its declared
Imagine that we have a class Vehicle with two subclasses, Car and Bicycle (Figure 8.9). In
this case, the typing rule admits that the following assignments are all legal:
Vehicle v1 = new Vehicle();
Vehicle v2 = new Car();
Vehicle v3 = new Bicycle();
Figure 8.9
An inheritance
Search WWH ::

Custom Search