Java Reference
In-Depth Information
14 on = false ;
15 }
16
17 public void setChannel( int newChannel) {
18 if (on && newChannel >= 1 && newChannel <= 120 )
19 channel = newChannel;
20 }
21
22 public void setVolume( int newVolumeLevel) {
23 if (on && newVolumeLevel >= 1 && newVolumeLevel <= 7 )
24 volumeLevel = newVolumeLevel;
25 }
26
27 public void channelUp() {
28 if (on && channel < 120 )
29 channel++;
30 }
31
32 public void channelDown() {
33 if (on && channel > 1 )
34 channel—-;
35 }
36
37 public void volumeUp() {
38 if (on && volumeLevel < 7 )
39 volumeLevel++;
40 }
41
42 public void volumeDown() {
43 if (on && volumeLevel > 1 )
44 volumeLevel—-;
45 }
46 }
set a new channel
set a new volume
increase channel
decrease channel
increase volume
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 9.4 gives a program that uses the TV class to create two objects.
L ISTING 9.4
TestTV.java
1 public class TestTV {
2 public static void main(String[] args) {
3 TV tv1 = new TV();
4 tv1.turnOn();
5 tv1.setChannel( 30 );
6 tv1.setVolume( 3 );
7
8 TV tv2 = new TV();
9 tv2.turnOn();
10 tv2.channelUp();
11 tv2.channelUp();
12 tv2.volumeUp();
13
14 System.out.println( "tv1's channel is " + tv1.channel
15 + " and volume level is " + tv1.volumeLevel);
16 System.out.println( "tv2's channel is " + tv2.channel
17 + " and volume level is " + tv2.volumeLevel);
18 }
19 }
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
 
 
Search WWH ::




Custom Search