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
9.4
Classes and objects can be represented using UML notation.
The method is denoted as
methodName(parameterName: parameterType): returnType
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 9.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
displays 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
.
avoid naming conflicts
L
ISTING
9.1
TestSimpleCircle.java
1
public class
TestSimpleCircle {
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
;
// or circle2.setRadius(100)
21 System.out.println(
"The area of the circle of radius "
22 + circle2.radius +
" is "
+ circle2.getArea());
main class
main
method
create object
create object
create object
Search WWH ::
Custom Search