Java Reference
In-Depth Information
The main class contains the main method (line 3) that creates three objects. As in creating an
array, the new operator is used to create an object from the constructor: new SimpleCircle()
creates an object with radius 1 (line 5), new SimpleCircle(25) creates an object with radius
25 (line 10), and new SimpleCircle(125) creates an object with radius 125 (line 15).
These three objects (referenced by circle1 , circle2 , and circle3 ) have different
data but the same methods. Therefore, you can compute their respective areas by using
the getArea() method. The data fields can be accessed via the reference of the object
using circle1.radius , circle2.radius , and circle3.radius , respectively. The
object can invoke its method via the reference of the object using circle1.getArea() ,
circle2.getArea() , and circle3.getArea() , respectively.
These three objects are independent. The radius of circle2 is changed to 100 in line 20.
The object's new radius and area are displayed in lines 21-22.
There are many ways to write Java programs. For instance, you can combine the two
classes in the example into one, as shown in Listing 9.2.
L ISTING 9.2
SimpleCircle.java
1 public class SimpleCircle {
2 /** Main method */
3 public static void main(String[] args) {
4 // Create a circle with radius 1
5 SimpleCircle circle1 = new SimpleCircle();
6 System.out.println( "The area of the circle of radius "
7 + circle1.radius + " is " + circle1.getArea());
8
9 // Create a circle with radius 25
10 SimpleCircle circle2 = new SimpleCircle( 25 );
11 System.out.println( "The area of the circle of radius "
12 + circle2.radius + " is " + circle2.getArea());
13
14 // Create a circle with radius 125
15 SimpleCircle circle3 = new SimpleCircle( 125 );
16 System.out.println( "The area of the circle of radius "
17 + circle3.radius + " is " + circle3.getArea());
18
19 // Modify circle radius
20 circle2.radius = 100 ;
21 System.out.println( "The area of the circle of radius "
22 + circle2.radius + " is " + circle2.getArea());
23 }
24
25
main method
double radius;
data field
26
27 /** Construct a circle with radius 1 */
28 SimpleCircle() {
29 radius = 1 ;
30 }
31
32 /** Construct a circle with a specified radius */
33 SimpleCircle( double newRadius) {
34 radius = newRadius;
35 }
36
37
no-arg constructor
second constructor
/** Return the area of this circle */
38
double getArea() {
method
39
return radius * radius * Math.PI;
40 }
41
 
 
Search WWH ::




Custom Search