- •CONTENTS
- •1.1 Introduction
- •1.2 What Is a Computer?
- •1.3 Programs
- •1.4 Operating Systems
- •1.5 Java, World Wide Web, and Beyond
- •1.6 The Java Language Specification, API, JDK, and IDE
- •1.7 A Simple Java Program
- •1.8 Creating, Compiling, and Executing a Java Program
- •1.9 (GUI) Displaying Text in a Message Dialog Box
- •2.1 Introduction
- •2.2 Writing Simple Programs
- •2.3 Reading Input from the Console
- •2.4 Identifiers
- •2.5 Variables
- •2.7 Named Constants
- •2.8 Numeric Data Types and Operations
- •2.9 Problem: Displaying the Current Time
- •2.10 Shorthand Operators
- •2.11 Numeric Type Conversions
- •2.12 Problem: Computing Loan Payments
- •2.13 Character Data Type and Operations
- •2.14 Problem: Counting Monetary Units
- •2.15 The String Type
- •2.16 Programming Style and Documentation
- •2.17 Programming Errors
- •2.18 (GUI) Getting Input from Input Dialogs
- •3.1 Introduction
- •3.2 boolean Data Type
- •3.3 Problem: A Simple Math Learning Tool
- •3.4 if Statements
- •3.5 Problem: Guessing Birthdays
- •3.6 Two-Way if Statements
- •3.7 Nested if Statements
- •3.8 Common Errors in Selection Statements
- •3.9 Problem: An Improved Math Learning Tool
- •3.10 Problem: Computing Body Mass Index
- •3.11 Problem: Computing Taxes
- •3.12 Logical Operators
- •3.13 Problem: Determining Leap Year
- •3.14 Problem: Lottery
- •3.15 switch Statements
- •3.16 Conditional Expressions
- •3.17 Formatting Console Output
- •3.18 Operator Precedence and Associativity
- •3.19 (GUI) Confirmation Dialogs
- •4.1 Introduction
- •4.2 The while Loop
- •4.3 The do-while Loop
- •4.4 The for Loop
- •4.5 Which Loop to Use?
- •4.6 Nested Loops
- •4.7 Minimizing Numeric Errors
- •4.8 Case Studies
- •4.9 Keywords break and continue
- •4.10 (GUI) Controlling a Loop with a Confirmation Dialog
- •5.1 Introduction
- •5.2 Defining a Method
- •5.3 Calling a Method
- •5.4 void Method Example
- •5.5 Passing Parameters by Values
- •5.6 Modularizing Code
- •5.7 Problem: Converting Decimals to Hexadecimals
- •5.8 Overloading Methods
- •5.9 The Scope of Variables
- •5.10 The Math Class
- •5.11 Case Study: Generating Random Characters
- •5.12 Method Abstraction and Stepwise Refinement
- •6.1 Introduction
- •6.2 Array Basics
- •6.3 Problem: Lotto Numbers
- •6.4 Problem: Deck of Cards
- •6.5 Copying Arrays
- •6.6 Passing Arrays to Methods
- •6.7 Returning an Array from a Method
- •6.8 Variable-Length Argument Lists
- •6.9 Searching Arrays
- •6.10 Sorting Arrays
- •6.11 The Arrays Class
- •7.1 Introduction
- •7.2 Two-Dimensional Array Basics
- •7.3 Processing Two-Dimensional Arrays
- •7.4 Passing Two-Dimensional Arrays to Methods
- •7.5 Problem: Grading a Multiple-Choice Test
- •7.6 Problem: Finding a Closest Pair
- •7.7 Problem: Sudoku
- •7.8 Multidimensional Arrays
- •8.1 Introduction
- •8.2 Defining Classes for Objects
- •8.3 Example: Defining Classes and Creating Objects
- •8.4 Constructing Objects Using Constructors
- •8.5 Accessing Objects via Reference Variables
- •8.6 Using Classes from the Java Library
- •8.7 Static Variables, Constants, and Methods
- •8.8 Visibility Modifiers
- •8.9 Data Field Encapsulation
- •8.10 Passing Objects to Methods
- •8.11 Array of Objects
- •9.1 Introduction
- •9.2 The String Class
- •9.3 The Character Class
- •9.4 The StringBuilder/StringBuffer Class
- •9.5 Command-Line Arguments
- •9.6 The File Class
- •9.7 File Input and Output
- •9.8 (GUI) File Dialogs
- •10.1 Introduction
- •10.2 Immutable Objects and Classes
- •10.3 The Scope of Variables
- •10.4 The this Reference
- •10.5 Class Abstraction and Encapsulation
- •10.6 Object-Oriented Thinking
- •10.7 Object Composition
- •10.8 Designing the Course Class
- •10.9 Designing a Class for Stacks
- •10.10 Designing the GuessDate Class
- •10.11 Class Design Guidelines
- •11.1 Introduction
- •11.2 Superclasses and Subclasses
- •11.3 Using the super Keyword
- •11.4 Overriding Methods
- •11.5 Overriding vs. Overloading
- •11.6 The Object Class and Its toString() Method
- •11.7 Polymorphism
- •11.8 Dynamic Binding
- •11.9 Casting Objects and the instanceof Operator
- •11.11 The ArrayList Class
- •11.12 A Custom Stack Class
- •11.13 The protected Data and Methods
- •11.14 Preventing Extending and Overriding
- •12.1 Introduction
- •12.2 Swing vs. AWT
- •12.3 The Java GUI API
- •12.4 Frames
- •12.5 Layout Managers
- •12.6 Using Panels as Subcontainers
- •12.7 The Color Class
- •12.8 The Font Class
- •12.9 Common Features of Swing GUI Components
- •12.10 Image Icons
- •13.1 Introduction
- •13.2 Exception-Handling Overview
- •13.3 Exception-Handling Advantages
- •13.4 Exception Types
- •13.5 More on Exception Handling
- •13.6 The finally Clause
- •13.7 When to Use Exceptions
- •13.8 Rethrowing Exceptions
- •13.9 Chained Exceptions
- •13.10 Creating Custom Exception Classes
- •14.1 Introduction
- •14.2 Abstract Classes
- •14.3 Example: Calendar and GregorianCalendar
- •14.4 Interfaces
- •14.5 Example: The Comparable Interface
- •14.6 Example: The ActionListener Interface
- •14.7 Example: The Cloneable Interface
- •14.8 Interfaces vs. Abstract Classes
- •14.9 Processing Primitive Data Type Values as Objects
- •14.10 Sorting an Array of Objects
- •14.11 Automatic Conversion between Primitive Types and Wrapper Class Types
- •14.12 The BigInteger and BigDecimal Classes
- •14.13 Case Study: The Rational Class
- •15.1 Introduction
- •15.2 Graphical Coordinate Systems
- •15.3 The Graphics Class
- •15.4 Drawing Strings, Lines, Rectangles, and Ovals
- •15.5 Case Study: The FigurePanel Class
- •15.6 Drawing Arcs
- •15.7 Drawing Polygons and Polylines
- •15.8 Centering a String Using the FontMetrics Class
- •15.9 Case Study: The MessagePanel Class
- •15.10 Case Study: The StillClock Class
- •15.11 Displaying Images
- •15.12 Case Study: The ImageViewer Class
- •16.1 Introduction
- •16.2 Event and Event Source
- •16.3 Listeners, Registrations, and Handling Events
- •16.4 Inner Classes
- •16.5 Anonymous Class Listeners
- •16.6 Alternative Ways of Defining Listener Classes
- •16.7 Problem: Loan Calculator
- •16.8 Window Events
- •16.9 Listener Interface Adapters
- •16.10 Mouse Events
- •16.11 Key Events
- •16.12 Animation Using the Timer Class
- •17.1 Introduction
- •17.2 Buttons
- •17.3 Check Boxes
- •17.4 Radio Buttons
- •17.5 Labels
- •17.6 Text Fields
- •17.7 Text Areas
- •17.8 Combo Boxes
- •17.9 Lists
- •17.10 Scroll Bars
- •17.11 Sliders
- •17.12 Creating Multiple Windows
- •18.1 Introduction
- •18.2 Developing Applets
- •18.3 The HTML File and the <applet> Tag
- •18.4 Applet Security Restrictions
- •18.5 Enabling Applets to Run as Applications
- •18.6 Applet Life-Cycle Methods
- •18.7 Passing Strings to Applets
- •18.8 Case Study: Bouncing Ball
- •18.9 Case Study: TicTacToe
- •18.10 Locating Resources Using the URL Class
- •18.11 Playing Audio in Any Java Program
- •18.12 Case Study: Multimedia Animations
- •19.1 Introduction
- •19.2 How is I/O Handled in Java?
- •19.3 Text I/O vs. Binary I/O
- •19.4 Binary I/O Classes
- •19.5 Problem: Copying Files
- •19.6 Object I/O
- •19.7 Random-Access Files
- •20.1 Introduction
- •20.2 Problem: Computing Factorials
- •20.3 Problem: Computing Fibonacci Numbers
- •20.4 Problem Solving Using Recursion
- •20.5 Recursive Helper Methods
- •20.6 Problem: Finding the Directory Size
- •20.7 Problem: Towers of Hanoi
- •20.8 Problem: Fractals
- •20.9 Problem: Eight Queens
- •20.10 Recursion vs. Iteration
- •20.11 Tail Recursion
- •APPENDIXES
- •INDEX
264Chapter 8 Objects and Classes
8.1Introduction
|
Having learned the material in earlier chapters, you are able to solve many programming prob- |
||||
|
lems using selections, loops, methods, and arrays. However, these Java features are not suffi- |
||||
|
cient for developing graphical user interfaces and large-scale software systems. Suppose you |
||||
|
want to develop a GUI (graphical user interface, pronounced goo-ee) as shown in Figure 8.1. |
||||
why OOP? |
How do you program it? |
|
|
|
|
|
Button |
Label |
Text Field Check Box |
Radio Button |
Combo Box |
|
FIGURE 8.1 The GUI objects are created from classes. |
||
|
This chapter begins the introduction of object-oriented programming, which will enable |
||
|
you to develop GUI and large-scale software systems effectively. |
||
|
8.2 Defining Classes for Objects |
||
object |
Object-oriented programming (OOP) involves programming using objects. An object repre- |
||
|
sents an entity in the real world that can be distinctly identified. For example, a student, a |
||
|
desk, a circle, a button, and even a loan can all be viewed as objects. An object has a unique |
||
|
identity, state, and behavior. |
||
state |
■ The state of an object (also known as its properties or attributes) is represented by |
||
|
data fields with their current values. A circle object, for example, has a data field |
||
|
radius, which is the property that characterizes a circle. A rectangle object has data |
||
|
fields width and height, which are the properties that characterize a rectangle. |
||
behavior |
■ The behavior of an object (also known as its actions) is defined by methods. To |
||
|
invoke a method on an object is to ask the object to perform an action. For example, |
||
|
you may define a method named getArea() for circle objects. A circle object may |
||
|
invoke getArea() to return its area. |
||
|
Objects of the same type are defined using a common class. A class is a template, blueprint, |
||
contract |
or contract that defines what an object’s data fields and methods will be. An object is an |
||
|
instance of a class. You can create many instances of a class. Creating an instance is referred |
||
instantiation |
to as instantiation. The terms object and instance are often interchangeable. The relationship |
||
object |
between classes and objects is analogous to that between an apple-pie recipe and apple pies. |
||
instance |
You can make as many apple pies as you want from a single recipe. Figure 8.2 shows a class |
||
|
named Circle and its three objects. |
||
|
|
|
A class template |
|
|
|
Circle Object 2 |
Circle Object 3 |
|
Three objects of |
||
|
|||||
Data Fields: |
Data Fields: |
|
the Circle class |
||
|
|
||||
radius is 25 |
radius is 125 |
|
|
||
|
|
|
|
|
|
FIGURE 8.2 A class is a template for creating objects.
8.2 Defining Classes for Objects 265
A Java class uses variables to define data fields and methods to define actions. Additionally, a class provides methods of a special type, known as constructors, which are invoked to create a new object. A constructor can perform any action, but constructors are designed to perform initializing actions, such as initializing the data fields of objects. Figure 8.3 shows an example of defining the class for circle objects.
class Circle { |
|
|
|||||
/** The radius of this circle */ |
|
|
|||||
double radius = 1.0; |
|
|
|
|
|
|
Data field |
|
|
|
|
|
|
||
/** Construct a circle object */ |
|
|
|
|
|||
|
|
|
|
|
|||
Circle() { |
|
|
|
||||
} |
|
|
|
|
|
|
Constructors |
/** Construct a circle object */ |
|
|
|
||||
|
|
|
|||||
|
|
|
|||||
Circle(double newRadius) { |
|
|
|
||||
radius = newRadius; |
|
|
|
||||
} |
|
|
|
|
|
|
|
/** Return the area of this circle */ |
|
|
|||||
double getArea() { |
|
|
|
|
Method |
||
|
|
|
|
||||
return radius * radius * Math.PI; |
|
|
|||||
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class data field method
constructor
FIGURE 8.3 A class is a construct that defines objects of the same type.
The Circle class is different from all of the other classes you have seen thus far. It does |
|
||||
not have a main method and therefore cannot be run; it is merely a definition for circle |
|
||||
objects. The class that contains the main method will be referred to in this book, for conve- |
|
||||
nience, as the main class. |
|
|
|
main class |
|
The illustration of class templates and objects in Figure 8.2 can be standardized using UML |
|
||||
(Unified Modeling Language) notations. This notation, as shown in Figure 8.4, is called a UML |
|
||||
class diagram, or simply a class diagram. In the class diagram, the data field is denoted as |
class diagram |
||||
dataFieldName: dataFieldType |
|
|
|
|
|
|
|
|
|
|
|
UML Class Diagram |
Circle |
|
|
Class name |
|
|
|
|
|||
|
radius: double |
|
|
Data fields |
|
|
|
|
|
||
|
|
|
|
Constructors and |
|
|
Circle() |
|
|
|
|
|
|
|
|
||
|
Circle(newRadius: double) |
|
|
methods |
|
|
|
|
|
|
|
|
getArea(): double |
|
|
|
|
|
|
|
|
|
|
circle1: Circle |
circle2: Circle |
|
circle3: Circle |
|
|
UML notation |
|
|
|
|
|||||
|
|
|
|
|
|
|
for objects |
radius = 10 |
radius = 25 |
|
radius = 125 |
||||
|
|
|
|
FIGURE 8.4 Classes and objects can be represented using UML notations.
The constructor is denoted as
ClassName(parameterName: parameterType)
The method is denoted as
methodName(parameterName: parameterType): returnType
266Chapter 8 Objects and Classes
8.3Example: Defining Classes and Creating Objects
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. To avoid a naming conflict with several improved versions of the Circle class introduced later in this book, the Circle class in this example is named Circle1.
The program constructs three circle objects with radius 1.0, 25, and 125 and displays the radius and area of each of the three circles. Change the radius of the second object to 100 and display its new radius and area.
|
LISTING 8.1 |
TestCircle1.java |
|||||||||||||||||
main class |
1 |
public class TestCircle1 { |
|||||||||||||||||
|
2 |
|
/** Main method */ |
||||||||||||||||
main method |
3 |
|
public static void main(String[] args) { |
||||||||||||||||
|
4 |
|
|
// Create a circle with radius 1.0 |
|||||||||||||||
create object |
5 |
|
|
Circle1 circle1 = new Circle1(); |
|
||||||||||||||
|
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 |
|||||||||||||||
create object |
10 |
|
|
Circle1 circle2 = new Circle1(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 |
|||||||||||||||
create object |
15 |
|
|
Circle1 circle3 = new Circle1(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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
// Define the circle class with two constructors |
|||||||||||||||||
class Circle1 |
27 |
class Circle1 { |
|||||||||||||||||
data field |
28 |
|
double radius |
; |
|
|
|
|
|
|
|
|
|
|
|||||
|
29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
/** Construct a circle with radius 1 */ |
||||||||||||||||
no-arg constructor |
31 |
|
Circle1() |
{ |
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
32 |
|
|
radius = 1.0; |
|||||||||||||||
|
33 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
/** Construct a circle with a specified radius */ |
||||||||||||||||
second constructor |
36 |
|
Circle1(double newRadius) |
{ |
|
|
|
|
|
|
|
||||||||
|
37 |
|
|
radius = newRadius; |
|||||||||||||||
|
38 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
|
/** Return the area of this circle */ |
||||||||||||||||
method |
41 |
|
double getArea() |
{ |
|
|
|
|
|
|
|
|
|
|
|
||||
|
42 |
|
|
return radius * radius * Math.PI; |
|||||||||||||||
|
43 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8.3 Example: Defining Classes and Creating Objects 267
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, TestCircle1, is the main class. Its sole |
|
purpose is to test the second class, Circle1. 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 system |
client |
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. |
public class |
Furthermore, the public class must have the same name as the file name. Therefore, the file |
|
name is TestCircle1.java, since TestCircle1 is public. |
|
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 Circle1() |
|
creates an object with radius 1.0 (line 5), new Circle1(25) creates an object with radius 25 |
|
(line 10), and new Circle1(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 is 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 8.2. |
|
LISTING 8.2 Circle1.java
1 |
public class Circle1 |
{ |
|
|
2 |
|
/** Main method */ |
|
|
3 |
|
public static void main(String[] args) { |
main method |
|
4 |
|
// Create a circle with radius 1.0 |
|
5Circle1 circle1 = new Circle1();
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
10Circle1 circle2 = new Circle1(25);
11System.out.println("The area of the circle of radius "
12+ circle2.radius + " is " + circle2.getArea());
13
14// Create a circle with radius 125
15Circle1 circle3 = new Circle1(125);
16System.out.println("The area of the circle of radius "
17+ circle3.radius + " is " + circle3.getArea());
18
19// Modify circle radius
20circle2.radius = 100;
21System.out.println("The area of the circle of radius "
22+ circle2.radius + " is " + circle2.getArea());
23}
24
268 Chapter 8 |
Objects and Classes |
|||||
data field |
25 |
|
double radius; |
|||
|
26 |
|
|
|
|
|
|
27 |
|
/** Construct a circle with radius 1 */ |
|||
no-arg constructor |
28 |
|
Circle1() |
{ |
||
|
29 |
|
radius = 1.0; |
|||
|
30 |
} |
|
|
|
|
|
31 |
|
|
|
|
|
|
32 |
|
/** Construct a circle with a specified radius */ |
|||
second constructor |
33 |
|
Circle1(double newRadius) |
{ |
||
|
34 |
|
radius = newRadius; |
|||
|
35 |
} |
|
|
|
|
|
36 |
|
|
|
|
|
|
37 |
|
/** Return the area of this circle */ |
|||
method |
38 |
|
double getArea() |
{ |
|
|
|
39 |
|
return radius * radius * Math.PI; |
|||
|
40 |
} |
|
|
|
|
|
41 |
} |
|
|
|
|
Since the combined class has a main method, it can be executed by the Java interpreter. The main method is the same as in Listing 1.1. This demonstrates that you can test a class by simply adding a main method in the same class.
As another example, consider TV sets. Each TV is an object with states (current channel, current volume level, power on or off) and behaviors (change channels, adjust volume, turn on/off). You can use a class to model TV sets. The UML diagram for the class is shown in Figure 8.5.
Listing 8.3 gives a program that defines the TV class.
|
|
|
channel: int |
|
|
volumeLevel: int |
|
|
on: boolean |
|
|
|
|
|
+TV() |
|
Constructs a default TV object. |
+turnOn(): void |
|
Turns on this TV. |
+turnOff(): void |
|
Turns off this TV. |
+setChannel(newChannel: int): void |
|
Sets a new channel for this TV. |
+setVolume(newVolumeLevel: int): void |
|
Sets a new volume level for this TV. |
+channelUp(): void |
|
Increases the channel number by 1. |
+channelDown(): void |
|
Decreases the channel number by 1. |
+volumeUp(): void |
|
Increases the volume level by 1. |
+volumeDown(): void |
|
Decreases the volume level by 1. |
|
|
|
FIGURE 8.5 The TV class models TV sets.
LISTING 8.3 TV.java
|
1 |
public class TV |
{ |
|
|
|
|
|
data fields |
2 |
|
int channel = |
1; |
// Default channel is 1 |
|||
|
3 |
|
int volumeLevel = 1; |
// Default volume level is 1 |
||||
|
4 |
|
boolean on = false; |
|
// By default TV is off |
|||
|
5 |
|
|
|
|
|
|
|
constructor |
6 |
|
public TV() { |
|
|
|
|
|
|
7 |
} |
|
|
|
|
|
|
|
8 |
|
|
|
|
|
|
|
|
8.3 |
Example: Defining Classes and Creating Objects 269 |
||
|
|
|
||
9 |
public void turnOn() { |
|
turn on TV |
|
10 |
on = true; |
|
||
11 |
} |
|
|
|
12 |
|
|
|
|
13 |
public void turnOff() { |
|
turn off TV |
14on = false;
15}
16 |
|
|
17 |
public void setChannel(int newChannel) { |
set a new channel |
18if (on && newChannel >= 1 && newChannel <= 120)
19channel = newChannel;
20}
21 |
|
|
22 |
public void setVolume(int newVolumeLevel) { |
set a new volume |
23if (on && newVolumeLevel >= 1 && newVolumeLevel <= 7)
24volumeLevel = newVolumeLevel;
25}
26 |
|
|
27 |
public void channelUp() { |
increase channel |
28if (on && channel < 120)
29channel++;
30}
31 |
|
|
32 |
public void channelDown() { |
decrease channel |
33if (on && channel > 1)
34channel--;
35}
36 |
|
|
37 |
public void volumeUp() { |
increase volume |
38if (on && volumeLevel < 7)
39volumeLevel++;
40}
41 |
|
|
42 |
public void volumeDown() { |
decrease volume |
43if (on && volumeLevel > 1)
44volumeLevel--;
45}
46}
Note that the channel and volume level are not changed if the TV is not on. Before either of these is changed, its current value is checked to ensure that it is within the correct range.
Listing 8.4 gives a program that uses the TV class to create two objects.
LISTING 8.4 TestTV.java
1 public class TestTV {
2 public static void main(String[] args) {
3TV tv1 = new TV();
4tv1.turnOn();
5tv1.setChannel(30);
6 |
tv1.setVolume(3); |
7 |
|
8TV tv2 = new TV();
9tv2.turnOn();
10tv2.channelUp();
11tv2.channelUp();
12tv2.volumeUp();
14System.out.println("tv1's channel is " + tv1.channel
15+ " and volume level is " + tv1.volumeLevel );
main method create a TV turn on
set a new channel set a new volume
create a TV turn on
increase channel
increase volume
display state