Java Reference
In-Depth Information
42
43
/** Return area */
44
public double getArea() {
45
return width * height;
46 }
47
48
/** Return perimeter */
49
public double getPerimeter() {
50
return 2 * (width + height);
51 }
52 }
The code in Listing 11.4 creates objects of Circle and Rectangle and invokes the methods
on these objects. The toString() method is inherited from the GeometricObject class
and is invoked from a Circle object (line 5) and a Rectangle object (line 13).
L ISTING 11.4
TestCircleRectangle.java
1 public class TestCircleRectangle {
2 public static void main(String[] args) {
3 CircleFromSimpleGeometricObject circle =
4 new CircleFromSimpleGeometricObject( 1 );
5 System.out.println( "A circle " + circle.toString());
6 System.out.println( "The color is " + circle.getColor());
7 System.out.println( "The radius is " + circle.getRadius());
8 System.out.println( "The area is " + circle.getArea());
9 System.out.println( "The diameter is " + circle.getDiameter());
10
11 RectangleFromSimpleGeometricObject rectangle =
12 new RectangleFromSimpleGeometricObject( 2 , 4 );
13 System.out.println( "\nA rectangle " + rectangle.toString());
14 System.out.println( "The area is " + rectangle.getArea());
15 System.out.println( "The perimeter is " +
16
Circle object
invoke toString
invoke getColor
Rectangle object
invoke toString
rectangle.getPerimeter());
17 }
18 }
A circle created on Thu Feb 10 19:54:25 EST 2011
color: white and filled: false
The color is white
The radius is 1.0
The area is 3.141592653589793
The diameter is 2.0
A rectangle created on Thu Feb 10 19:54:25 EST 2011
color: white and filled: false
The area is 8.0
The perimeter is 12.0
Note the following points regarding inheritance:
Contrary to the conventional interpretation, a subclass is not a subset of its superclass.
In fact, a subclass usually contains more information and methods than its superclass.
more in subclass
Private data fields in a superclass are not accessible outside the class. Therefore,
they cannot be used directly in a subclass. They can, however, be accessed/mutated
through public accessors/mutators if defined in the superclass.
private data fields
 
 
Search WWH ::




Custom Search