? c ?¥???
) ?3 ?¥???àQ[#3 ??0 ?¥1"
)D
P¨?
e? Q S P U F D U a G J O B M a B C T U S B D U
) ?3
??
)
P¨¤ g?=? ?
)
??? 7?¥V?? ?¥
!9e5
6.1 3 ??0 ?
Circle Circle Methods Circle Data
Superclass
Inheritance
Cylinder
Circle Methods
Cylinder Methods
Circle Data
Cylinder Data
Subclass
Circle
-radius
+getRadius
+setRadius
+findArea
Cylinder
-length
+getLength
+setLength
+findVolume
SubclassSuperclass
UML Diagram
Creating a Subclass
Creating a subclass extends data and methods
from the superclass. You can also:
) Add new data
) Add new methods
) Override the methods of the superclass
Cylinder Class
Example 6.1
Testing Inheritance
)Objective: Create a Cylinder object and
explore the relationship between the
Cylinder and Circle classes.
TestCylinder Run
6.2 The Object Class
)The Object class is the root of all Java classes.
)The toString() method returns a string
representation of the object.
)The equals() method compares the
contents of two objects.
)The clone() method copy objects
6.3 ?
e?
The protected Modifier
)protected?
e??¨? ?¥
? ?ZE
b ??1¥
? ZE V[$]
B?¥?? ?
?¥0 ?`ù'
P0
??]¥?9 V[ b
The protected Modifier
pacakge p1
class C1
protected int x
class C3
C1 c1;
c1.x can be read or
modified
pacakge p2
class C2 extends C1
x can be read or
modified in C2
class C4
C1 c1;
c1.x cannot be read
nor modified
C1? C3
]B
??
C2
^ C1
¥0 ?
C4D C1
?]
B?
?
The final Modifier
)The final class cannot be extended:
final class Math
{...}
)The final variable is a constant:
final static double PI = 3.14159;
)The final method cannot be
modified by its subclasses.
The abstract Modifier
)The abstract class
– Cannot be instantiated
– Should be extended and implemented in
subclasses
)The abstract method
– Method signature without
implementation
6.4
????
?t?
)
?? (polymorphism)
^B? ?
?Mi1??
T b
) Java? V[]B ??] ??
?l ?M]??T?]¥?ZE
??·¥
^?
H???3?'?
ZE}
?¥? ? b??? ?9?S?
?
t? b
6.5 The instanceof Operator
Use the instanceof operator to test whether
an object is an instance of a class:
Circle myCircle = new Circle();
if (myCircle instanceof Cylinder)
{
Cylinder myCylinder = (Cylinder)myCircle;
...
}
6.6 ¤ g
? Java?
?×??'B? ??
?
?
?×??'B? ??
?
μ?3 ?ào?μB?3 ? b
μ?3 ?ào?μB?3 ? b
Java?|}×??¥/
?
^¤ g b
?|}×??¥/
?
^¤ g b
Java
^¨¤ g/
?¥ey
^y1×
^¨¤ g/
?¥ey
^y1×
??1
1
PIrdèˉ1
1r
q
??1
1
PIrdèˉ1
1r
q
?ú