This Keyword
Team Teach
This
Keyword
General
this
keyword is used as a reference to the object itself- It can be used to reference the object’s instance variables, methods, constructors, etc.
- Enables instance variables to access an object’s variables and methods
- It is used to avoid confusion between instance variables and parameter values
public class F {
private int i = 5;
public void setI(int i) {
this.i = i; //this.i refers to the instance variable i
// i refers to the parameter i
}
}
Calling Another Constructor
this
keyword can be used to invoke another constructor of the same class
Format: this.(argument)
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius; //this keyword references the hidden data field, radius
}
public Circle() {
this(1.0); //passes 1.0 as an argument to the 1st constructor
}
}
Calling Other Methods
- this keyword can be used to call other methods in the same class
Format: this.methodName()
public class Robot {
private String name;
public Robot(String name) {
this.name = name;
}
public void start() {
System.out.println(this.name + " is starting up...");
this.speak(); // Calls the speak method of the current object
}
public void speak() {
System.out.println(this.name + " says: 'Hello, human!'");
}
}
Popcorn Hacks
public class Minion {
private String eyeCount;
private int height;
public minion(String eyeCount, int height) {
this.eyeCount = eyeCount;
this.height = height;
}
public void setHeight(int height) {
this.height = height;
}
public String getEyeCount() {
return this.eyeCount;
}
public boolean isTallerThan(Minion otherMinion) {
return this.height > otherMinion.height;
}
public static void main(String[] args) {
Minion minion1 = new Minion(1, 28);
Minion minion2 = new Minion(2, 43);
System.out.println("minion 1 number of eyes: " + minion1.getEyeCount());
System.out.println("Is minion1 taller than minion2? " + minion1.isTallerThan(minion2));
minion2.setHeight(50);
System.out.println("Is minion1 still taller than minion2? " + minion1.isTallerThan(minion2));
}
}
-
What is the output of the statement System.out.println(“minion 1 eyeCount: “ + minion1.getEyeCount());? Explain why the this keyword is useful in the getEyeCount() method.
-
What does the isTallerThan() method compare? How does the this keyword play a role in this comparison?
-
What happens to the result of System.out.println(“Is minion1 taller than minion2? “ + minion1.isTallerThan(minion2)); after minion2.setHeight(50); is called? Why does the result change?
-
Do minion1 and minion2 refer to the same object in memory?