Junior — Middle
What is the purpose of using the keyword 'this' in programming code?
sobes.tech AI
Answer from AI
The this keyword in Java is used to refer to the current object, within which a method or constructor is being executed. It helps to:
- Distinguish between the object's fields and method or constructor parameters with the same names.
- Pass the current object as an argument to other methods.
- Call other constructors within a constructor (using
this(...)).
Example:
public class Person {
private String name;
public Person(String name) {
this.name = name; // this.name is the object's field, name is the parameter
}
public void printName() {
System.out.println(this.name); // referring to the current object's field
}
}