คืนค่าการตั้งค่าทั้งหมด
คุณแน่ใจว่าต้องการคืนค่าการตั้งค่าทั้งหมด ?
ลำดับตอนที่ #18 : Java V - Associating Vehicle and Person
Class
type Fields
Defining
Vehicle Owners
Now let's learn a bit about
associations. Using the Person class from
Java IV, let's make a program in which a person can own a vehicle.
Class
Type Fields
We can create a class instance as a
field by declaring a variable of class type. Let's create an instance field
called owner of type Person like in the example below.
Getter
and Setter
Next let's define getter and setter
methods. We'll define them in the same way that we learned previously, but note
that the getter's return value and the setter's parameter are class types.
Return
Value of Instance
When we call the getOwner method with an instance of the Car/ Bicycle
class, the return value will be the value of the owner
field, that is, an instance
of the Person class. As shown below on the left, we can call the printData method (an instance method of the Person class) right after the getOwner method.
The
buy Method
Defining
the buy Method
Let's define the buy method so that a
Person class instance can purchase a vehicle. Each vehicle is an instance of
the Car class or the Bicycle class. The argument of the buy method should
accept an instance of either type, so we need to overload the method (see
below).
buy
Method
Inside the buy
method, change the owner using an instance taken as an argument to the setter
method.
Polymorphism
Duplicate
Code in the buy Method
Let's take another look at the buy method. Here we find a problem: each time we
make a subclass of the Vehicle superclass,
we need to define another method with the same name that takes a different
argument type in each subclass.
Improving
the buy Method
There is a way to solve this problem. As
shown in the examples below, by accepting an instance of the Vehicle type as a parameter, the buy method is able to take an instance of the Car class as well as the Bicycle
class.
Assigning
Subclass Instances to Superclass Variables
Since the Car class inherits the Vehicle class, an instance of the Car class is also type Vehicle. When this relationship is found, we can assign an instance of a subclass to the class type variable of a superclass. This is why we can change the class type of the buy method's argument to Vehicle (this is called polymorphism).
ความคิดเห็น