Java Tutorial 13 – “this” keyword

This video takes you through a practical scenario where you will have to use “this” keyword.


Please be patient . Video will load in some time. If you still face issue viewing video click here

Points to Remember:

  • “this” is a reference to the current object, whose method is being called upon.
  • You can use “this” keyword to avoid naming conflicts in the method/constructor of your instance/object.

Assignment: To learn the use “this” keyword

Step 1 ) Copy the following code into a notepad.

class Account{
int a;
int b;

 public void setData(int a ,int b){
  a = a;
  b = b;
 }
 public void showData(){
   System.out.println("Value of A ="+a);
   System.out.println("Value of B ="+b);
 }
 public static void main(String args[]){
   Account obj = new Account();
   obj.setData(2,3);
   obj.showData();
 }
}

Step 2 ) Save ,Compile & Run the code.

Step 3 )  Value of a & b is shown as zero ? To correct the error append line # 6 & 7with “this” keyword.

this.a =a;
this.b=b;

Step 4) Save ,Compile & Run the code. This time around , values of a & b are set to 2 & 3 respectively.