0% completed
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.
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.this Keyword to Access Member VariablesIn this example, we demonstrate how the this keyword differentiates between class members and constructor parameters in the Car class.
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.
.....
.....
.....