Java Reference
In-Depth Information
UML Class Diagram
Circle
Class name
Data fields
radius: double
Circle()
Circle(newRadius: double)
getArea(): double
getPerimeter(): double
setRadius(newRadius: double): void
Constructors and
methods
UML notation
for objects
circle1: Circle
circle2: Circle
circle3: Circle
radius = 1
radius = 25
radius = 125
F IGURE 8.4
Classes and objects can be represented using UML notation.
The method is denoted as
methodName(parameterName: parameterType): returnType
8.3 Example: Defining Classes and Creating Objects
Classes are definitions for objects and objects are created from classes.
Key
Point
This section gives two examples of defining classes and uses the classes to create objects.
Listing 8.1 is a program that defines the Circle class and uses it to create objects. The pro-
gram constructs three circle objects with radius 1 , 25 , and 125 and displays the radius and
area of each of the three circles. It then changes the radius of the second object to 100 and dis-
plays its new radius and area.
Note
To avoid a naming conflict with several enhanced versions of the Circle class intro-
duced later in the chapter, the Circle class in this example is named SimpleCircle .
For simplicity, we will still refer to the class in the text as Circle .
L ISTING 8.1 TestSimpleCircle.java
1
avoid naming conflicts
public class TestSimpleCircle {
main class
2
/** Main method */
3
public static void main(String[] args) {
main method
4
// Create a circle with radius 1
5
6 System.out.println( "The area of the circle of radius "
7 +
SimpleCircle circle1 = new SimpleCircle();
create object
circle1.radius
+ " is " +
circle1.getArea()
);
8
9
// Create a circle with radius 25
SimpleCircle circle2 = new SimpleCircle( 25 );
10
11 System.out.println( "The area of the circle of radius "
12 + circle2.radius + " is " + circle2.getArea());
13
14
create object
// Create a circle with radius 125
15
16 System.out.println( "The area of the circle of radius "
17 + circle3.radius + " is " + circle3.getArea());
18
19 // Modify circle radius
20 // or circle2.setRadius(100)
21 System.out.println( "The area of the circle of radius "
22 +
SimpleCircle circle3 = new SimpleCircle( 125 );
create object
circle2.radius = 100 ;
circle2.radius
circle2.getArea()
+ " is " +
);
23 }
 
 
 
Search WWH ::




Custom Search