Java Reference
In-Depth Information
14 on =
false
;
15 }
16
17
18
if
(on && newChannel >=
1
&& newChannel <=
120
)
19 channel = newChannel;
20 }
21
22
23
if
(on && newVolumeLevel >=
1
&& newVolumeLevel <=
7
)
24 volumeLevel = newVolumeLevel;
25 }
26
27
28
if
(on && channel <
120
)
29 channel++;
30 }
31
32
33
if
(on && channel >
1
)
34 channel—-;
35 }
36
37
38
if
(on && volumeLevel <
7
)
39 volumeLevel++;
40 }
41
42
43
if
(on && volumeLevel >
1
)
44 volumeLevel—-;
45 }
46 }
public void
setChannel(
int
newChannel) {
set a new channel
public void
setVolume(
int
newVolumeLevel) {
set a new volume
public void
channelUp() {
increase channel
public void
channelDown() {
decrease channel
public void
volumeUp() {
increase volume
public void
volumeDown() {
decrease volume
The constructor and methods in the
TV
class are defined public so they can be accessed from
other classes. 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.
L
ISTING
8.4
TestTV.java
1
public class
TestTV {
2
public static void
main(String[] args) {
main
method
create a TV
turn on
set a new channel
set a new volume
TV tv1 =
new
TV();
3
4 tv1.turnOn();
5 tv1.setChannel(
30
);
6 tv1.setVolume(
3
);
7
8
9 tv2.turnOn();
10 tv2.channelUp();
11 tv2.channelUp();
12 tv2.volumeUp();
13
14 System.out.println(
"tv1's channel is "
+
15 +
" and volume level is "
+ );
16 System.out.println(
"tv2's channel is "
+ tv2.channel
17 +
" and volume level is "
+ tv2.volumeLevel);
18 }
19 }
TV tv2 =
new
TV();
create a TV
turn on
increase channel
increase volume
tv1.channel
display state
tv1.volumeLevel