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.

The this keyword has very much importance in Java programming language.Let us look into a program below that demonstrate the working of 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());

}

}

 

 


For more of such hot topics read my other posts here :

Visit my new website

Article Written by jontymagicman

I am DInesh Varyani.


Post Your Comment