Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Program to demonstrate this keyword to find area of rectangle

How to use the this keyword in Java ?.
The this keyword is a special keyword frequently used in the Java programming language. Usually, this keyword is used when we want to refer currently executing object. Here this keyword is the reference to a calling object itself. When a object calls a method also called as Instance method, it has variable this which refers to object which has called it. By using this keyword you can refer or access to any field of a particular object in a method or constructor. Whenever an instance method or constructor is called this keyword is set to a variable holding reference to a object who has called it.

package com.hubberspot.this.example;

class Rectangle{
    
  private int length;
  private int breadth;
    
  Rectangle(int length){
    this.length = length;
  }
    
  Rectangle(int length, int breadth){
    this(length);
    this.breadth = breadth;       
  }
  public int area(){
    return (length*breadth);
  } 
}

public class ThisTest {
  public static void main(String [] args){
    Rectangle rect = new Rectangle(5,5);
        
    System.out.println("The Area of rectangle is : "+
        + rect.area());
    
    }
    
}

Output of the program :- 

 
© 2021 Learn Java by Examples Template by Hubberspot