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 and MAX_Y. It also has two int fields, a and b.
  • 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 another UseOfThis 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());



This was an example of how to use the keyword this to call a constructor in a class in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button