This keyword in Java

this keyword in Java

1.this is a keyword that refers to the current object of class.
2.It can be used to replace local variable with class level variable.
3.It is also used to call current class method/function.
4.It is also used to call current class overloaded constructor.

1. this keyword as a variable hiding

By using this keywrod we can replace local variable with instance varible. For better understanding see the below example.

  class Rectangle
  {
    //declaring instance variable
    int height=10,width=20;
    public void area()
    {
     //declaring local varibael
    int height=5,width=6,ar;
    //using local variable
    ar=height*width;
    System.out.println("Area 1="+ar);
    //using class level(instance) variable
    ar=this.height*this.width;
    System.out.println("Area 2="+ar);
    }  
  }
class Easy
{
 public static void main(String[] args)
 {
  //Creating instance(object) of  class
  Rectangle obj=new Rectangle();
  //calling class function
  obj.area();
 }
}
/*
### Output ###
Area 1=30
Area 2=200
*/

2. this keyword with function

By using this keywrod we can also call a function of class without creating instance(object) of that class. For better understanding see the below example.

  class Geometry
  {
    
    public void rectangle_area(int height,int width)
    {
    int ar=height*width;
    System.out.println("Area of rectangle="+ar);
    }
    public void square_area(int side)
    {
    int ar=side*side;
    System.out.println("Area of square="+ar);
    //calling function using this keyword
    this.rectangle_area(12, 13);
    }
  }
class Easy
{
 public static void main(String[] args)
 {
  //Creating instance(object) of  class
  Geometry obj=new Geometry();
  //calling class function
  obj.square_area(12);
 }
}
/*
### Output ###
Area of square=144
Area of rectangle=156
*/

3. this keyword constructor

By using this keywrod we can also call a function of class without creating instance(object) of that class. For better understanding see the below example.

  class Rectangle
  {
    //parameterised constructor
    Rectangle(int height,int width)
    {
    int ar=height*width;
    System.out.println("Area of rectangle="+ar);
    }
    //default constructor
    public Rectangle() 
    {
     //calling parameterised constructor
     this(12,13);  
        System.out.println("I am inside default constructor");
    }
  }
class Easy
{
 public static void main(String[] args)
 {
  //Creating instance(object) of  class
  Rectangle obj=new Rectangle();
 }
}
/*
### Output ###
Area of rectangle=156
I am inside default constructor
*/
Next Post Previous Post
No Comment
Add Comment
comment url