The this Keyword

By: aathishankaran  

The this Keyword

    Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class type is permitted.

    To better understand what this refers to, consider the following program 

class Box {

double width;

double height;

double depth;


Box ( double w, double h, double) {

    width = w;

    height = h;

    depth = d;



double volume(){

    return width * height * depth;




class BoxDemo {

    public static void main (string args[]) {

        Box mybox1 = new Box (10,20,15);


        double vol;


        vol = mybox2.volume();

        System.out.println("Volume is" + vol);




In this program we can use the below coding for defining the values for the data member by using this keyword

Box ( double w, double h, double) {

    this.width = w;

    this.height = h;

    this.depth = d;


    This coding for Box() also operates exactly like the pervious Box() code. The use of this is redundant, but perfectly correct. Inside Box(), this will always refer to the invoking object. Here this refers the current variable. While it is redundant in this case, this is useful in other contexts, in some particular situations.

Archived Comments

1. good. very nice.
View Tutorial          By: anuprassana at 2007-03-03 04:22:42

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial