Java如何使用“ this”关键字?
每个实例方法都有一个名为this的变量,该变量引用调用该方法的当前对象。可以使用此关键字从实例方法或构造函数中引用当前对象的任何成员。
每次调用实例方法时,this变量都会被设置为引用应用它的特定类对象。然后,方法中的代码将与该关键字引用的对象的特定成员相关。
package org.nhooo.example.fundamental;
public class RemoteControl {
private String channelName;
private int channelNum;
private int minVolume;
private int maxVolume;
RemoteControl() {
}
RemoteControl(String channelName, int channelNum) {
// 使用this关键字在
// 同班
this(channelName, channelNum, 0, 0);
}
RemoteControl(String channelName, int channelNum, int minVol, int maxVol) {
this.channelName = channelName;
this.channelNum = channelNum;
this.minVolume = minVol;
this.maxVolume = maxVol;
}
public void changeVolume(int x, int y) {
this.minVolume = x;
this.maxVolume = y;
}
public static void main(String[] args) {
RemoteControl remote = new RemoteControl("ATV", 10);
// 当执行以下行时,此变量位于
// changeVolume()是引用远程对象。
remote.changeVolume(0, 25);
}
}
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短