Java Reference
In-Depth Information
7
8 System.out.println( "The two objects have the same area? " +
9
equalArea(geoObject1, geoObject2));
10
11 // Display circle
12 displayGeometricObject(geoObject1);
13
14 // Display rectangle
15 displayGeometricObject(geoObject2);
16 }
17
18
/** A method for comparing the areas of two geometric objects */
19
public static boolean equalArea(GeometricObject object1,
equalArea
20
GeometricObject object2) {
21
return object1.getArea() == object2.getArea();
22 }
23
24 /** A method for displaying a geometric object */
25 public static void displayGeometricObject(GeometricObject object) {
26 System.out.println();
27 System.out.println( "The area is " + object.getArea());
28 System.out.println( "The perimeter is " + object.getPerimeter());
29 }
30 }
displayGeometricObject
The two objects have the same area? false
The area is 78.53981633974483
The perimeter is 31.41592653589793
The area is 13.0
The perimeter is 16.0
The methods getArea() and getPerimeter() defined in the GeometricObject class are
overridden in the Circle class and the Rectangle class. The statements (lines 5-6)
GeometricObject geoObject1 = new Circle( 5 );
GeometricObject geoObject2 = new Rectangle( 5 , 3 );
create a new circle and rectangle and assign them to the variables geoObject1 and
geoObject2 . These two variables are of the GeometricObject type.
When invoking equalArea(geoObject1, geoObject2) (line 9), the getArea()
method defined in the Circle class is used for object1.getArea() , since geoObject1
is a circle, and the getArea() method defined in the Rectangle class is used for
object2.getArea() , since geoObject2 is a rectangle.
Similarly, when invoking displayGeometricObject(geoObject1) (line 12), the
methods getArea() and getPerimeter() defined in the Circle class are used, and when
invoking displayGeometricObject(geoObject2) (line 15), the methods getArea and
getPerimeter defined in the Rectangle class are used. The JVM dynamically determines
which of these methods to invoke at runtime, depending on the actual object that invokes the
method.
Note that you could not define the equalArea method for comparing whether two geomet-
ric objects have the same area if the getArea method were not defined in GeometricObject .
Now you have seen the benefits of defining the abstract methods in GeometricObject .
why abstract methods?
 
 
Search WWH ::




Custom Search