Java Reference
In-Depth Information
43
44 @Override
45
public
String toString() {
46
return
"created on "
+ dateCreated +
"\ncolor: "
+ color +
47
" and filled: "
+ filled;
48 }
49
50
/** Abstract method getArea */
51
public abstract double
getArea();
abstract method
52
53
/** Abstract method getPerimeter */
abstract method
54
public abstract double
getPerimeter();
55 }
Abstract classes are like regular classes, but you cannot create instances of abstract classes
using the
new
operator. An abstract method is defined without implementation. Its implemen-
tation is provided by the subclasses. A class that contains abstract methods must be defined
as abstract.
The constructor in the abstract class is defined as protected, because it is used only by
subclasses. When you create an instance of a concrete subclass, its superclass's constructor is
invoked to initialize data fields defined in the superclass.
The
GeometricObject
abstract class defines the common features (data and methods)
for geometric objects and provides appropriate constructors. Because you don't know how to
compute areas and perimeters of geometric objects,
getArea()
and
getPerimeter()
are
defined as abstract methods. These methods are implemented in the subclasses. The imple-
mentation of
Circle
and
Rectangle
is the same as in Listings 13.2 and 13.3, except that
they extend the
GeometricObject
class defined in this chapter. You can see the complete
code for these two programs from
www.cs.armstrong.edu/liang/intro10e/html/Circle.html
and
www.cs.armstrong.edu/liang/intro10e/html/Rectangle.html,
respectively.
why protected constructor?
implement
Circle
implement
Rectangle
L
ISTING
13.2
Circle.java
1
public class
Circle
extends
GeometricObject {
2
extends abstract
GeometricObject
// Same as lines 3-48 in Listing 11.2, so omitted
3 }
L
ISTING
13.3
Rectangle.java
1
public class
Rectangle
extends
GeometricObject {
2
extends abstract
GeometricObject
// Same as lines 3-51 in Listing 11.3, so omitted
3 }
13.2.1 Why Abstract Methods?
You may be wondering what advantage is gained by defining the methods
getArea()
and
getPerimeter()
as abstract in the
GeometricObject
class. The example in Listing 13.4
shows the benefits of defining them in the
GeometricObject
class. The program creates two
geometric objects, a circle and a rectangle, invokes the
equalArea
method to check whether
they have equal areas, and invokes the
displayGeometricObject
method to display them.
L
ISTING
13.4
TestGeometricObject.java
1
public class
TestGeometricObject {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Create two geometric objects
5
GeometricObject geoObject1 =
new
Circle(
5
);
create a circle
create a rectangle
6
GeometricObject geoObject2 =
new
Rectangle(
5
,
3
);
Search WWH ::
Custom Search