What is the usage method of the Java keyword “this”?
The Java keyword “this” is a reference that points to the current object.
There are several ways to use the keyword “this.”
- In the constructor, used to call another constructor when creating an object. This call must be on the first line of the constructor. For example:
- Call another constructor by passing the parameter x and 0.
- In instance methods, it is used to refer to the current object. It is typically used to distinguish between instance variables and method parameters. For example:
- The “this” keyword is used to refer to the instance variable of the current object.
- In an inner class, used to reference an instance of the outer class. If the inner class and outer class have the same member variable or method name, the outer class instance can be referenced using the “this” keyword.
For example: - The public class OuterClass contains a private variable x, and it also contains a public class InnerClass. The InnerClass has its own private variable x and a method printX() that prints the values of both its own x and the x of the OuterClass.
In essence, the “this” keyword is primarily used in a constructor to call another constructor, reference instance variables of the current object, and reference the instance of the outer class in an inner class.