this keyword in java - in constructor, refer instance variable, call instance method, this (current class object) as a parameter, return this, acquire object lock


Usage of this keyword in java -

1) Using this() in constructor

2) this keyword can be used to refer instance variable of same class
3) Using this to call instance method of same class>

4) Using this (current class object) as a parameter, object is passed as a reference

5) return this (current class object)

6) this can be used to acquire object lock



1) Using this() in constructor
  • this() can be used to call constructor of same class.
  • this() helps in using some other constructor of same class, hence avoid writing of any redundant code.
  • this() can be used only in constructor of class to call some other constructor of same class (Please ensure that this() must be be first line of constructor, else you will face compilation error)

Program to use this() for calling some other constructor of same class>
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
  
   int id;
   String name;
   //Constructor 1 with id only.
   MyClass(int i){  
          id=i;
   }
   //Constructor 2 with id and name.
   MyClass(int i, String na){
          this(i); //use Constructor 1 and
                       //avoid writing redundant code of that constructor here.
          name=na;
   }
  
   public static void main(String[] args) {
          //Passing only id > will call Constructor 1
          MyClass obj1=new MyClass(1);
         
          //Passing id and name > Constructor 2
          MyClass obj2=new MyClass(1);
   }
}

In the above program this(i) calls Constructor 1 and hence we avoid writing code of constructor 1 in  constructor 2.

Now, what if we wouldn’t have used this(i)?
Our constructor 2 would have looked like this-
   //Constructor 2 with id and name.
   MyClass(int i, String na){
          id=i;
          name=na;
   }
We unnecessarily would have ended up writing code of constructor 1 in constructor 2. Imagine what if constructor 1 would have got thousands of line in it.



  • First line in constructor can either be super() or this(). But, super() and this() cannot be used in same constructor. (Please ensure that super() or this() whichever is used must be be first line of constructor, else you will face compilation error)
We read in above points that compiler implicitly adds super() as first line of constructor, but if we add this() explicitly than compiler doesn’t add super()

Program to understand usage of this() and super() in constructor and also to show this() and super() cannot be used in same constructor >
class SuperClass{
   SuperClass(){
         System.out.println("no-arg constructor of SuperClass");
   }
}
class SubClass extends SuperClass{
   SubClass(){
          this(1);
          System.out.println("no-arg constructor of SubClass");
   }
   SubClass(int i){
          super();
          System.out.println("int-arg constructor of SubClass");
   }
  
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass{
   public static void main(String[] args) {
      new SubClass(); //will call constructor of SubClass
   }
}
/* OUTPUT
no-arg constructor of SuperClass
int-arg constructor of SubClass
no-arg constructor of SubClass
*/



2) this keyword can be used to refer instance variable of same class
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
  
   int i; //instance variable
  
   /*
   * constructor
   */
   MyClass(int i){ //i is argument
         
          this.i=i; //this.i > refers to instance variable
                        //i      > refers to argument
   }
  
   public static void main(String[] args) {
          MyClass obj=new MyClass(1);
   }
}

In the above program, name of instance variable is same as that of argument, so we used this keyword to differentiate between them -
this.i > refers to instance variable
    i      > refers to argument

Now, you must be wondering what if name of instance variable is not same as that of argument?
In that case this keyword won’t be required, though it may be used optionally.
Let’s create very small program to understand the same>
public class MyClass {
   int i;
   MyClass(int j){
          this.i=j;
   }  
}
In the above program using this.i is optional, we may only i as well.



3) Using this to call instance method of same class>
instance method of class can only be called only from instance method of same class.

Program for using this to call instance method of same class >
public class MyClass {
  
   public static void main(String[] args) {
          MyClass obj=new MyClass();
          obj.m1();
   }
  
     //instance method
   void m1(){
          this.m2();  // Or use  m2()  only
   }
  
     //instance method
   void m2(){
         
   }
  
}
In the above program this.m2() was called from m1().
Using this.m2() is equivalent to calling m2().





4) Using this (current class object) as a parameter, object is passed as a reference


Program for using this (current class object) as a parameter
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
  
   int i;
  
   public static void main(String[] args) {
          MyClass obj=new MyClass();
          obj.i=2;
         
          System.out.println(obj.i); //print obj.i (will print 2)
          obj.m1();
          System.out.println(obj.i); //print obj.i again (will print 3),
                                     //after m1() internally called m2(this)     
   }
  
   void m1(){
          m2(this); //passing this (current class object) as argument,
                       //object is passed as a reference
   }
  
   void m2(MyClass obj1){
          obj1.i=3; //obj1 and obj are referring to same object.
                 //So, any changes to obj1 will be reflected in obj as well or vice-versa.
   }
  
}
/* OUTPUT
2
3
*/
In the above program, m1() was called from main method, m1() internally called m2(this), by using this (current class object) as a parameter, object was passed as a reference, so any changes made to obj1 in m1 were reflected in obj as well. That’s why when obj.i was printed again it printed updated value (i.e. 3).


5) return this (current class object)

Program to return this (current class object)>
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
  
   int i;
  
   public static void main(String[] args) {
          MyClass obj1=new MyClass(); //create obj1
          obj1.i=2;
         
          MyClass obj2=new MyClass(); //create obj2
          obj2=obj1.m();  //method m() will return this
         
          //Now, obj1 and obj2 are referring to same object.
          //So, any changes to obj2 will be reflected in obj1 as well or vice-versa.
          System.out.println("print obj1.i and obj2.i, both must be same");
          System.out.println("obj1.i= "+ obj1.i);
          System.out.println("obj2.i= "+ obj2.i);
         
          obj2.i=3; //change to obj2.i will be reflected in obj1.i as well.
         
          System.out.println("print obj1.i and obj2.i after making changes to obj2.i "
                                     + ",both must be same");
          System.out.println("obj1.i= "+ obj1.i);
          System.out.println("obj2.i= "+ obj2.i);
         
   }
   /*
   * method returns this (current class object)
   */
   MyClass m(){
          return this; //return current class object
   }
}
/* OUTPUT
print obj1.i and obj2.i, both must be same
obj1.i= 2
obj2.i= 2
print obj1.i and obj2.i after making changes to obj2.i ,both must be same
obj1.i= 3
obj2.i= 3
*/
In the above program, m() returned this (current class object).
So, obj1 and obj2 were referring to same object, that’s why any changes to obj2 were reflected in obj1 as well.
We printed obj1.i and obj2.i after making changes to obj2.i and both were same.



6) this can be used to acquire object lock
      synchronized (this) {
        //thread has acquired lock on current object.
      }


RELATED LINKS>


Super keyword in java - Invoke constructor, Access instance variable, Invoke instance method of immediate super class using super

No comments:

Post a Comment