Java Reference
In-Depth Information
24 }
25
26 // Define the circle class with two constructors
27 class SimpleCircle {
28
class SimpleCircle
data field
double radius
;
29
30
/** Construct a circle with radius 1 */
SimpleCircle()
31
{
no-arg constructor
32 radius = 1 ;
33 }
34
35
/** Construct a circle with a specified radius */
36
SimpleCircle( double newRadius)
{
second constructor
37 radius = newRadius;
38 }
39
40
/** Return the area of this circle */
double getArea()
41
{
getArea
42
return radius * radius * Math.PI;
43 }
44
45
/** Return the perimeter of this circle */
46
double getPerimeter()
{
getPerimeter
47
return 2 * radius * Math.PI;
48 }
49
50
/** Set a new radius for this circle */
void setRadius( double newRadius)
51
{
setRadius
52 radius = newRadius;
53 }
54 }
The area of the circle of radius 1.0 is 3.141592653589793
The area of the circle of radius 25.0 is 1963.4954084936207
The area of the circle of radius 125.0 is 49087.385212340516
The area of the circle of radius 100.0 is 31415.926535897932
The program contains two classes. The first of these, TestSimpleCircle , is the main class.
Its sole purpose is to test the second class, SimpleCircle . Such a program that uses the class
is often referred to as a client of the class. When you run the program, the Java runtime sys-
tem invokes the main method in the main class.
You can put the two classes into one file, but only one class in the file can be a public class .
Furthermore, the public class must have the same name as the file name. Therefore, the file
name is TestSimpleCircle.java , since TestSimpleCircle is public. Each class in the source
code is compiled into a .class file. When you compile TestSimpleCircle.java , two class files
TestSimpleCircle.class and SimpleCircle.class are generated, as shown in Figure 8.5.
client
public class
// File TestSimpleCircle.java
TestSimpleCircle.class
generates
public class TestSimpleCircle {
}
Java
Compiler
compiled
by
class SimpleCircle {
}
generates
SimpleCircle.class
F IGURE 8.5
Each class in the source code file is compiled into a .class file.
 
Search WWH ::




Custom Search