The keyword this refers to the object itself. It can also be used inside a constructor to invoke another constructor of the same class.
The this keyword is the name of a reference that an object can use to refer to itself. You can use the this keyword to reference the object’s instance members. For example, the following code in (a) uses this to reference the object’s radius and invokes its getArea() method explicitly. The this reference is normally omitted, as shown in (b). However, the this reference is needed to reference hidden data fields or invoke an overloaded constructor.
Using this to Reference Hidden Data Fields
The this keyword can be used to reference a class’s hidden data fields. For example, a datafield name is often used as the parameter name in a setter method for the data field. In this case, the data field is hidden in the setter method. You need to reference the hidden data-field name in the method in order to set a new value to it. A hidden static variable can be accessed simply by using the ClassName.staticVariable reference. A hidden instance variable can be accessed by using the keyword this, as shown in Figure below (a).
The this keyword gives us a way to reference the object that invokes an instance method. To invoke f1.setI(10), this.i = i is executed, which assigns the value of parameter i to the data field i of this calling object f1. The keyword this refers to the object that invokes the instance method setI, as shown in Figure above (b). The line F.k = k means that the value in parameter k is assigned to the static data field k of the class, which is shared by all the objects of the class.
Using this to Invoke a Constructor
The this keyword can be used to invoke another constructor of the same class. For example, you can rewrite the Circle class as follows:
The line this(1.0) in the second constructor invokes the first constructor with a double value argument. Java requires that the this(arg-list) statement appear first in the constructor before any other executable statements. If a class has multiple constructors, it is better to implement them using this(arg-list) as much as possible. In general, a constructor with no or fewer arguments can invoke a constructor with more arguments using this(arg-list). This syntax often simplifies coding and makes the class easier to read and to maintain.
Top comments (0)