Skip to content
C

this Keyword

this refers to the current object — the specific object whose method or constructor is currently running. It's often used to distinguish between a class field and a parameter that share the same name.


1. What is the this Keyword?

this refers to the current object — the specific object whose method or constructor is currently running. It's often used to distinguish between a class field and a parameter that share the same name.

2. Why is it used?

When a constructor or method parameter has the same name as a class field, Java needs a way to tell them apart. this clearly points to the object's own field, avoiding confusion with the parameter.

3. Real-Life Example

Think of a person saying "my house" to refer specifically to their own house, even when several houses are being discussed. this works the same way — pointing specifically to the current object's own data.

4. Syntax

java
this.fieldName = parameterName;

5. Example Program

java
class Student { String name; Student(String name) { this.name = name; // this.name = field, name = parameter } } public class ThisDemo { public static void main(String[] args) { Student s = new Student("Sneha"); System.out.println("Name: " + s.name); } }

Output:

Name: Sneha

6. Key Points to Remember

  • this always refers to the current object, never to a class in general.
  • It's most commonly used to resolve naming conflicts between fields and parameters.
  • this() (with parentheses) can also be used to call one constructor from another within the same class.