Java Reference
In-Depth Information
13
/** A method for displaying an object */
displayObject(Object object)
14
public static void
{
15
if (
object instanceof CircleFromSimpleGeometricObject
) {
16 System.out.println( "The circle area is " +
17 ((CircleFromSimpleGeometricObject)object).getArea());
18 System.out.println( "The circle diameter is " +
19 ((CircleFromSimpleGeometricObject)object).getDiameter());
20 }
21 else if (
22
polymorphic call
object instanceof
RectangleFromSimpleGeometricObject
) {
23 System.out.println( "The rectangle area is " +
24 ((RectangleFromSimpleGeometricObject)object).getArea());
25 }
26 }
27 }
polymorphic call
The circle area is 3.141592653589793
The circle diameter is 2.0
The rectangle area is 1.0
The displayObject(Object object) method is an example of generic programming. It
can be invoked by passing any instance of Object .
The program uses implicit casting to assign a Circle object to object1 and a
Rectangle object to object2 (lines 5-6), then invokes the displayObject method to dis-
play the information on these objects (lines 9-10).
In the displayObject method (lines 14-26), explicit casting is used to cast the object to
Circle if the object is an instance of Circle , and the methods getArea and getDiameter
are used to display the area and diameter of the circle.
Casting can be done only when the source object is an instance of the target class. The pro-
gram uses the instanceof operator to ensure that the source object is an instance of the tar-
get class before performing a casting (line 15).
Explicit casting to Circle (lines 17, 19) and to Rectangle (line 24) is necessary because
the getArea and getDiameter methods are not available in the Object class.
Caution
The object member access operator ( . ) precedes the casting operator. Use parentheses
to ensure that casting is done before the . operator, as in
precedes casting
((Circle)object).getArea());
Casting a primitive type value is different from casting an object reference. Casting a primi-
tive type value returns a new value. For example:
int age = 45 ;
byte newAge = ( int )age; // A new value is assigned to newAge
However, casting an object reference does not create a new object. For example:
Object o = new Circle();
Circle c = (Circle)o; // No new object is created
Now reference variables o and c point to the same object.
 
Search WWH ::




Custom Search