Monday, 20 January 2014

this KEYWORD IN JAVA

this  is a keyword in Java. Which can be used inside method or constructor of  class. It(this) works as a reference to current object whose method or constructor is being invoked. this keyword can be used to refer any member of current object from within an instance method or a constructor.


Syntax of using this keyword:

this.varName

Example 1 : Program that illustrates how this keyword can be used  with Constructor.

//example of this keyword
class Student{
    int id;
    String name;
   
    student(int id,String name)
{
    this.id = id;
    this.name = name;
    }
    void display(){System.out.println(id+" "+name);
}
    public static void main(String args[])
{
    Student s1 = new Student(985,"KRISHNA");
    Student s2 = new Student(432,"AATHI");
    s1.display();
    s2.display();  

Output:

985 KRISHNA
432 AATHI

Another use of the this keyword is it allows one constructor to explicitly invoke another constructor in the same class.

1.this KEYWORD WITH COSTRUCTOR


this keyword can be used inside Constructor to call another overloaded Constructor in same class. It is called Explicit Constructor Invocation. If a class has two overloaded constructor one without argument and another with argument. Then this keyword can be used to call Constructor with argument from Constructor without argument. As constructor can not be called explicitly.

Syntax to call another constructor of same class using this keyword: 

this(args);

Example 2 :Program that illustrates how this keyword can be used by one constructor to explicitly invoke another constructor in the same class

class Square
{
       int height;
       int width;

       Square()
       {
               this(0,0);
        }
        Square(int side)
        {
               this(side, side);
         }
         
         Square(int height, int width)
         {
                this.height = height;
                this.width = width;
          }
}

class ImplSquare
{
     public static void main(String args[])
     {
             Square sObj = new Square(4,6);
             
             System.out.println("Variable values of object : ");
             System.out.println("Object height =  " + sObj.height);
             System.out.println("Object width = " + sObj.width);
      }
}

Output

Variable values of object : 
Object height =  4
Object width =  6

2 comments :

  1. I stumbled across this article through another blog, and I do so wish I could get my head around this subject. Alin

    ReplyDelete
  2. Nice tutorial, This is very useful to me, Thanks for sharing this post.
    SEO Training in Chennai

    ReplyDelete