DEV Community

Athithya Sivasankarar
Athithya Sivasankarar

Posted on

Understanding the "this" Keyword in Java Using a SuperMarket Example

What is the "this" Keyword?

The "this" keyword is a reference variable that refers to the current object of a class.

Whenever an object calls a method, "this" refers to that particular object. It is commonly used to access instance variables and methods of the current object.

Program Example

public class SuperMarket {

String name;
int price;

public static void main(String args[]) {

    SuperMarket prod1 = new SuperMarket();

    prod1.name = "Rice";
    prod1.price = 1500;

    prod1.buy();
}

void buy() {

    // this refers to the current object
    System.out.println(this.price);
    System.out.println(this.name);
}
Enter fullscreen mode Exit fullscreen mode

}

Output

1500
Rice

Explanation

Step 1: Creating an Object

SuperMarket prod1 = new SuperMarket();

This statement creates an object named "prod1".

Step 2: Assigning Values

prod1.name = "Rice";
prod1.price = 1500;

The object now stores the following values:

Variable| Value
name| Rice
price| 1500

Step 3: Calling the Method

prod1.buy();

When the "buy()" method is called, the keyword "this" refers to the object "prod1".

Therefore,

this.price

is equivalent to

prod1.price

and

this.name

is equivalent to

prod1.name

As a result, the values stored in the object are printed on the screen.

Why Use the "this" Keyword?

The "this" keyword improves code readability and helps Java identify the current object's variables and methods.

It becomes especially useful when local variables and instance variables have the same name.

Example:

class Product {

String name;

Product(String name) {
    this.name = name;
}
Enter fullscreen mode Exit fullscreen mode

}

In the above code:

  • "this.name" refers to the instance variable.
  • "name" refers to the constructor parameter.

Without "this", Java cannot differentiate between the two variables.

Advantages of Using "this"

  • Refers to the current object.
  • Improves code readability.
  • Helps access instance variables and methods.
  • Useful in constructors.
  • Supports constructor chaining.
  • Makes object-oriented programming easier to understand.

Top comments (0)