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 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());
    }
}

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.

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.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button