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 教师闺蜜祝福语简短