Curriculum
In Java, “this” is a keyword that refers to the current object. When a method is called on an object, the “this” keyword can be used to refer to that object within the method.
Here’s an example:
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return this.name; } public int getAge() { return this.age; } }
In this example, the “this” keyword is used to refer to the current object within the constructor and the “getName” and “getAge” methods. In the constructor, “this.name” and “this.age” refer to the instance variables “name” and “age” of the current object. In the “getName” and “getAge” methods, “this.name” and “this.age” are used to refer to the instance variables of the current object as well.
The “this” keyword is useful in situations where there is ambiguity or confusion between local variables and instance variables of an object. By using “this”, you can be sure that you are referring to the instance variables of the current object, rather than local variables with the same name.
Here’s an example:
public class Calculator { private int result; public void add(int result) { this.result += result; } public int getResult() { return this.result; } }
In this example, the “add” method takes an integer parameter named “result”, which has the same name as the instance variable “result”. By using “this.result” within the method, we can be sure that we are updating the instance variable of the current object, rather than the local variable with the same name.