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 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短