Junior Bill gates Junior Bill gates - 2 months ago 8
Java Question

Use of "this" keyword in java

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 the
this
keyword is used when the name of an instance variables is same to the constructor function
parameters. Am I right or wrong?

Answer

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");
     }

}
Comments