Programming Tutorials

The this Keyword in Java

By: aathishankaran in Java Tutorials on 2007-03-03  

In Java, the this keyword refers to the current instance of the class. It can be used to refer to instance variables or methods of the current object.

Here's an example using a Box class:

public class Box {
    private int length;
    private int width;
    private int height;
    
    public Box(int length, int width, int height) {
        this.length = length;
        this.width = width;
        this.height = height;
    }
    
    public int getVolume() {
        return this.length * this.width * this.height;
    }
}

In the Box class, the constructor takes three parameters: length, width, and height. Inside the constructor, this is used to refer to the current object, and the instance variables length, width, and height are initialized with the values passed as arguments.

The getVolume() method uses this to refer to the current object and the instance variables length, width, and height to calculate and return the volume of the box.

Overall, this is a useful keyword in Java that allows you to refer to the current instance of the class and access its instance variables and methods.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)