class
Use the keyword this to call a constructor – Part 2
This is an example of how to use the keyword this to call a constructor of a class. Within an instance method or a constructor, this
keyword is a reference to the current object, that is the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this
keyword. We have created a class to show the keyword’s use:
UseOFThis
has two field, an int and a String.- It has a constructor to initialize its int field and another one to initialize its String field.
- It has a constructor where it initializes both fields, using the keyword
this
to call the instance’s constructor to initialize the int field with a given int value and then to get the object’s String field and set it to a given String. - It has a constructor without fields, where it uses the object’s constructor with fields, usign the keyword this again, this time with specified values.
- It has a
print()
method that prints the values of the object’s fields. - We create a new instance of
UseOfThis
and call itsprint()
method to print its fields’ values.
Let’s take a look at the code snippet that follows:
public class UseOfThis { int count = 0; String s = new String("null"); UseOfThis(int num) { count = num; System.out.println("Constructor int arg only, count= " + count); } UseOfThis(String ss) { System.out.println("Constructor String arg only, s=" + ss); s = ss; } UseOfThis(String s, int num) { this(num); //! this(s); // Can't call two! this.s = s; // Another use of "this" System.out.println("String & int args"); } UseOfThis() { this("hi", 47); System.out.println("default constructor (no args)"); } void print() { //! this(11); // Not inside non-constructor! System.out.println("count = " + count + " s = " + s); } public static void main(String[] args) { UseOfThis x = new UseOfThis(); x.print(); } }
Output:
Constructor int arg only, count= 47
String & int args
default constructor (no args)
count = 47 s = hi
This was an example of how to use the keyword this to call a constructor of a class in Java.