2.13 调用对象的行为
Android游戏开发详解
在前面的小节中,我们介绍了如何赋值和访问所创建的对象的状态。接下来,我们讨论方法,并且学习如何调用对象的行为。
调用方法也需要使用点运算符。我们使用点运算符来引用属于一个特定对象的具体的方法。在程序清单2.12的main方法的底部,添加如下所示的两行代码。
myPhone.togglePower();
myPhone.upgrade(4.5);
如果我们再回头来看看Phone类,会看到togglePower方法检查boolean poweredOn的当前值,并且对其取反(将ture变为false,将false变为true)。由于创建对象的时候,myPhone最初是打开的,我们期望myPhone现在关闭。我们还预测了myPhone的androidVersionNumber从4.4变为4.5。
为了测试这些,我们又一次打印出myPhone对象的状态,在main方法的底部添加一些打印语句,如程序清单2.13所示。
程序清单2.13 打印出myPhone的状态
01 public class World {
02
03 public static void main(String[] args) {
04 System.out.println("Hello, world!");
05 Phone myPhone = new Phone();
06 myPhone.poweredOn = true;
07 myPhone.playingMusic = false;
08 myPhone.phoneManufacturer = "Samsung";
09 myPhone.androidVersionNumber = 4.4;
10
11 System.out.println("myPhone's state:");
12 System.out.println("Powered on: " + myPhone.poweredOn);
13 System.out.println("Playing music: " + myPhone.playingMusic);
14 System.out.println("Manufacturer: " + myPhone.phoneManufacturer);
15 System.out.println("Version: " + myPhone.androidVersionNumber);
16
17 myPhone.togglePower();
18 myPhone.upgrade(4.5);
19
20 // include “\n” to skip a line when printing.
21 System.out.println("\nmyPhone's NEW state:");
22 System.out.println("Powered on: " + myPhone.poweredOn);
23 System.out.println("Playing music: " + myPhone.playingMusic);
24 System.out.println("Manufacturer: " + myPhone.phoneManufacturer);
25 System.out.println("Version: " + myPhone.androidVersionNumber);
26 }
27 }
相应的输出如下所示。
Hello, world!
myPhone's state:
Powered on: true
Playing music: false
Manufacturer: Samsung
Version: 4.4
Powering off!
myPhone's NEW state:
Powered on: false
Playing music: false
Manufacturer: Samsung
Version: 4.5
正如所预测那样,手机关闭了,并且其Android版本现在是4.5。我们能够调用myPhone行为来执行特定的操作,以修改myPhone的状态了。
时间: 2024-10-13 19:18:03