Java Intermediate

0% completed

Previous
Next
The 'this' Keyword

What is the this Keyword?

The this keyword in Java is a reference to the current object—the instance on which a method or constructor is being invoked. It plays a crucial role in differentiating between class members and parameters, especially when they share the same name.

  • Characteristics:
    • Used to refer to the current object's members (variables and methods).
    • Helps in distinguishing between class members and parameters with the same name.
    • Can be used to invoke other constructors within the same class.

Syntax of the this Keyword

class ClassName { // Class members dataType variableName; // Constructor ClassName(dataType variableName) { this.variableName = variableName; } // Method void methodName(dataType variableName) { this.variableName = variableName; } }

Explanation:

  • this.variableName: Refers to the class member variable.
  • variableName: Refers to the constructor or method parameter.

Example 1: Car Class Using the this Keyword to Access Member Variables

In this example, we demonstrate how the this keyword differentiates between class members and constructor parameters in the Car class.

Java
Java

. . . .

Explanation:

  • this.brand = brand;:
    Assigns the constructor parameter brand to the class member variable brand.

  • this.color = color;:
    Assigns the constructor parameter color to the class member variable color.

  • this.year = year;:
    Assigns the constructor parameter year to the class member variable year.

  • Car myCar = new Car("Tesla", "White", 2023);:
    Creates a new Car object myCar with the specified brand, color, and year.

The this keyword is a powerful tool in Java that references the current object. It is primarily used to distinguish between class member variables and parameters that share the same name, ensuring that assignments and method calls affect the intended variables.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next