Sunday, 2 April 2017

'this' keyword

lets discuss this keyword,this is a reference to the current class object.this can be used with respect to variables,methods and classes.

this with respect to variables:

this keyword is used to preserve the values of the instance variables.

What is an instance variable ?

A variable that is declared in the class is known as instance variable.Every object of that class will contain a copy of the variable.

Example:

class Code
{
 int var=10;//instance variable
 methodA()
 { 
  ----
  ---
 }
}



this to preserve instance variables:

import java.io.*;
class Code
{
 int var=15;
 methodA()
 { 
 int var=5;
 System.out.println("Local variable is"+var);
 System.out.println("Instance variable is"+this.var);
 }
}
class MainClass
{ 
  public static void main(String args[])
  { 
   Code c=new Code();
   c.methodA();
  }
}

Output:

Local variable is 5
Instance variable is 15

this with respect to methods:

As a general procedure,If we want to access a particular method, we create an object to that class and access the desired method. In this process 'this' is used implicitly.

import java.io.*;
class Code
{ 
 void methodA()
 { 
  System.out.println("Im in methodA of Code Class");
  this.methodB();
 }
 void methodB()
 {
   System.out.println("Im in methodB of Code Class");
 }
}
class MainClass
{ 
 public static void main(String args[])
 { 
  Code c=new Code();
  c.methodA();
 
 }
}

Output :

Im in methodA of Code Class
Im in methodB of Code Class

this with respect to constructors:

this keyword is used within a constructor to invoke another overloaded constructor.Usually this is placed in the first line of the calling constructor.

Example:

import java.io.*;
class Code
{
 Code()
 {
 this(5);
 System.out.println("inside the constructor without parameters");
 }
 Code(int a)
{
 System.out.println("Inside the overloaded constructor with int value "+a);
}
 public static void main(String args[])
 { 
 Code  c=new Code();//default constructor is called 
 }
}

Output :

Inside the overloaded constructor with int value 5
inside the constructor without parameters

1 comment: