每个实例方法都有一个名为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);
}
}