class
Use the keyword this to call a constructor
In this example we shall show you how to use the keyword this
to call a constructor in 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. To use the keyword this
to call a constructor we have performed the following steps:
- We have created a class
UseOfThis
, that has two final fields,MAX_X
andMAX_Y
. It also has two int fields,a
andb
. - It has a constructor to initialize its two int fields, using
this
keyword to get the object’s fields with two given int fields. - It has another constructor without fields, that calls the previous constructor, using
this
keyword, with arguments the two final fields divided by two. - It also has a
toString()
method that returns the int values. - We create a new instance of
UseOfThis
using two int fields as arguments. Then we create anotherUseOfThis
instance without fields. This constructor calls the first constructor as described above,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; public class UseOfThis { final static int MAX_X = 640, MAX_Y = 480; int a, b; UseOfThis(int a, int b) { this.a = a; this.b = b; } UseOfThis() { this(MAX_X / 2, MAX_Y / 2); // Use the constructor above } public String toString() { return "[" + a + "," + b + "]"; } public static void main(String[] av) { System.out.println(new UseOfThis(300, 100)); System.out.println(new UseOfThis()); } }
Output:
[300,100]
[320,240]
This was an example of how to use the keyword this
to call a constructor in a class in Java.