Java Reference
In-Depth Information
41
return dateCreated;
42 }
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
52
53
public abstract double getArea();
abstract method
/** Abstract method getPerimeter */
public abstract double getPerimeter();
54
55 }
abstract method
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 imple-
mentation 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 sub-
classes. 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
implementation of Circle and Rectangle is the same as in Listings 15.2 and 15.3, except
that they extend the GeometricObject class defined in this chapter.
why protected constructor?
implementing Circle
implementing Rectangle
L ISTING 15.2 Circle.java
1 public class Circle
extends GeometricObject
extends abstract
GeometricObject
{
2
// Same as lines 3-48 in Listing 11.2, so omitted
3 }
L ISTING 15.3 Rectangle.java
1 public class Rectangle
extends GeometricObject
{
extends abstract
GeometricObject
2
// Same as lines 3-51 in Listing 11.3, so omitted
3 }
15.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 15.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 15.4 TestGeometricObject.java
1 public class TestGeometricObject {
2
/** Main method */
3
public static void main(String[] args) {
4
// Create two geometric objects
5
6
GeometricObject geoObject1 = new Circle( 5 );
create a circle
create a rectangle
GeometricObject geoObject2 = new Rectangle( 5 , 3 );
 
Search WWH ::




Custom Search