Java Reference
In-Depth Information
Note
You can also pass an object to invoke
System.out.println(object)
or
System.out.print(object)
. This is equivalent to invoking
System.out
.println(object.toString())
or
System.out.print(object.
toString())
. Thus, you could replace
System.out.println(loan
.toString())
with
System.out.println(loan)
.
print object
Polymorphism means that a variable of a supertype can refer to a subtype object.
Key
Point
The three pillars of object-oriented programming are encapsulation, inheritance, and poly-
morphism. You have already learned the first two. This section introduces polymorphism.
First, let us define two useful terms: subtype and supertype. A class defines a type. A
type defined by a subclass is called a
subtype
, and a type defined by its superclass is called
a
supertype
. Therefore, you can say that
Circle
is a subtype of
GeometricObject
and
GeometricObject
is a supertype for
Circle
.
The inheritance relationship enables a subclass to inherit features from its superclass with
additional new features. A subclass is a specialization of its superclass; every instance of a
subclass is also an instance of its superclass, but not vice versa. For example, every circle
is a geometric object, but not every geometric object is a circle. Therefore, you can always
pass an instance of a subclass to a parameter of its superclass type. Consider the code in
Listing 11.5.
subtype
supertype
L
ISTING
11.5
PolymorphismDemo.java
1
public class
PolymorphismDemo {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Display circle and rectangle properties
5
displayObject(
new
CircleFromSimpleGeometricObject
polymorphic call
6
(
1
,
"red"
,
false
));
7
displayObject(
new
RectangleFromSimpleGeometricObject
polymorphic call
8
(
1
,
1
,
"black"
,
true
));
9 }
10
11
/** Display geometric object properties */
12
public static void
displayObject(SimpleGeometricObject object) {
13 System.out.println(
"Created on "
+ object.getDateCreated() +
14
". Color is "
+ object.getColor());
15 }
16 }
Created on Mon Mar 09 19:25:20 EDT 2011. Color is red
Created on Mon Mar 09 19:25:20 EDT 2011. Color is black
The method
displayObject
(line 12) takes a parameter of the
GeometricObject
type.
You can invoke
displayObject
by passing any instance of
GeometricObject
(e.g.,
new
CircleFromSimpleGeometricObject(1, "red", false)
and
new Rectangle-
FromSimpleGeometricObject(1, 1, "black", false)
in lines 5-8). An object of
a subclass can be used wherever its superclass object is used. This is commonly known as
polymorphism
(from a Greek word meaning “many forms”). In simple terms, polymorphism
means that a variable of a supertype can refer to a subtype object.
what is polymorphism?
Search WWH ::
Custom Search