Java Reference
In-Depth Information
overridden and to demonstrate subtype polymorphism.
class,leave
Circle
asis,andintroducea
Rectangle
classthatextends
Shape
.You
account. Check out the following
main()
method:
public static void main(String[] args)
{
Shape[] shapes = new Shape[] { new Point(10, 20), new
Circle(10, 20, 30),
new
Rectangle(20,
30,
15, 25) };
for (int i = 0; i < shapes.length; i++)
shapes[i].draw();
}
Because
Point
and
Rectangle
directly extend
Shape
, and because
Circle
indirectly extends
Shape
by extending
Point
,
main()
responds to
shapes[i].draw();
by calling the correct subclass's
draw()
method.
Although
Shape
makes the code more flexible, there is a problem. What is to
stop someone from instantiating
Shape
and adding this meaningless instance to the
shapes
array, as follows?
Shape[] shapes = new Shape[] { new Point(10, 20), new
Circle(10, 20, 30),
new Rectangle(20, 30, 15,
25), new Shape() };
What does it mean to instantiate
Shape
? Because this class describes an abstract
concept,whatdoesitmeantodrawagenericshape?Fortunately,Javaprovidesasolu-
tion to this problem, which is demonstrated in
Listing 2-37
.
Listing 2-37.
Abstracting the
Shape
class
abstract class Shape
{
abstract void draw(); // semicolon is required
}