Wednesday, 6 April 2016

This Keyword in Java

This Keyword in Java

Hello friends Today we will learn about This keyword in Java; this keyword is mainly used to refer to current object.
This Keyword in Java

Some Important points for remember about this keyword


  • this keyword is used to refer to current object.
  • this is always a reference to the object on which method was invoked.
  • this can be used to invoke current class constructor.
  • this can be passed as an argument to another method.

Example of this keyword

class Rectangle
 {
  int length;
  int breadth;
  void setDiamentions(int ln,int br)
  {
  this.length  = ln;
  this.breadth = br;
  }
}
class RectangleDemo
{
  public static void main(String args[])
 {
  Rectangle r1 = new Rectangle();
  r1.setDiamentions(20,10);
  System.out.println("Length of Rectangle : " + r1.length);
  System.out.println("Breadth of Rectangle : " + r1.breadth);
  }
}

Output :

Length  of Rectangle : 20
Breadth of Rectangle : 10

Whenever we define constructor then if the local parameter names and instance variable names are same then local parameters hide the instance variables(members of class)by overriding it, so to resolve this ambiguity "this" keyword is used.

class Demo
{
int a,b;
     Demo(int a,int b)
     {
        this.a=a;
        this.b=b;
       }
}

No comments:

Post a Comment