I was studying method overriding in Java when ai came across the this
keyword. After searching much about this on the Internet and other sources, I concluded that thethis
keyword is used when the name of an instance variables is same to the constructor function
parameters. Am I right or wrong?
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
Accessing member variables or functions There are situations when the name of a variable, which is a member of a class, is the same as that of the parameter. In such a case, using the this keyword is mandatory with the variable which is a member of the class; otherwise, the program won't compile.
In answer to "Are there any cases where you should always use this ?" You should use it when it is needed to avoid ambiguity, for example if there is another variable with the same name in scope.
The correct answer to the question “What is not the use of 'this' keyword in Java” is, option (d). Passing itself to the method of the same class. This is one of the most important keywords in Java and is used to distinguish between local variables and variables that are passed in the methods as parameters.
this
is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):
class Foo
{
private int bar;
public Foo() {
this(42); // invoke parameterized constructor
}
public Foo(int bar) {
this.bar = bar; // disambiguate
}
public void frob() {
this.baz(); // used "just because"
}
private void baz() {
System.out.println("whatever");
}
}
this
keyword can be used for (It cannot be used with static methods):
this
is used to invoke method of current class.ClassName.this
enclosingObjectReference.new EnclosedClass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With