Every instance method has a variable with the name this
that refers to the current object for which the method is being called. You can refer to any member of the current object from within an instance method or a constructor by using this
keyword.
Each time an instance method is called, the this
variable is set to reference the particular class object to which it is being applied. The code in the method will then relate to the specific members of the object referred to by this
keyword.
package org.kodejava.basic;
public class RemoteControl {
private String channelName;
private int channelNum;
private int minVolume;
private int maxVolume;
RemoteControl() {
}
RemoteControl(String channelName, int channelNum) {
// use "this" keyword to call another constructor in the
// same class
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 static void main(String[] args) {
RemoteControl remote = new RemoteControl("ATV", 10);
// when the following line is executed, the variable in
// changeVolume() is referring to remote object.
remote.changeVolume(0, 25);
}
public void changeVolume(int x, int y) {
this.minVolume = x;
this.maxVolume = y;
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024