4 This Keyword
4 This Keyword
Lecture Handout-4
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
Suggestion: If you are beginner to java, lookup only three usage of this keyword.
this keyword with a field(Instance Variable)
this keyword can be very useful in the handling of Variable Hiding. We can not
create two instances/local variables with the same name. However, it is legal
to create one instance variable & one local variable or Method parameter with
the same name. In this scenario, the local variable will hide the instance
variable this is called Variable Hiding.
class JBT {
int variable = 5;
obj.method(20);
obj.method();
}
void method() {
int variable = 40;
System.out.println("Value of variable :" +
variable);
}
}
COPY
As you can see in the example above, the instance variable is hiding, and the
value of the local variable (or Method Parameter) is displayed not instance
variable. To solve this problem use this keyword with a field to point to the
instance variable instead of the local variable.
class JBT {
int variable = 5;
obj.method(20);
obj.method();
}
void method() {
int variable = 40;
System.out.println("Value of Instance variable :" +
this.variable);
System.out.println("Value of Local variable :" +
variable);
}
}
COPY
class JBT {
JBT() {
this("JBT");
System.out.println("Inside Constructor without
parameter");
}
JBT(String str) {
System.out
.println("Inside Constructor with
String parameter as " + str);
}
As you can see “this” can be used to invoke an overloaded constructor in the
same Class.
Note*:
● this keyword can only be the first statement in Constructor.
● A constructor can have either this or super keyword but not both.
class JBT {
void methodTwo(){
System.out.println("Inside Method TWO");
this.methodOne();// same as calling methodOne()
}
}