Power of this keyword in Java

this keyword is a reference ( which means it manages some relation ) to the current object where it is called ( can be constructor,function etc). It helps to keep the control of scope to access variables or any other elements. thisĀ keyword is very powerful and widely used in complex Java application.

NOTE: All code is from Official documentation of Oracle Java.

for example, refer this piece of Java code.

public class Point {
public int x = 0;
public int y = 0;

//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}

so when we create object of “Point” class, constructor will assign the parameter values “a” and “b” to “x” and “y” declared globally in class. Pretty straight. Now take a look atĀ this code.

public class Point {
public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

Here we are using same name of parameters in constructor as well as global declared variables. Now let’s create the object of this class.

Point ob=new Point(10,20);

Here, 10 and 20 will be assigned to “x” and “y” of Point constructor and then again assigned to this.x (x declared in class globally) and this.y. That means we have differentiated the variable, whether it is from function call or defined in class globally using “this” keyword.

Can we call constructor from constructor ? Yes

You can use “this” keyword to call constructor from one constructor depending upon your need. Here is simple code to show how to do so. This is official doc example of Oracle.

public class Rectangle {
private int x, y;
private int width, height;

public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public static void main(String args[])throws Exception
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle(10,20);
Rectangle r3=new Rectangle(1,2,10,20);
}
}

Upon creation of Object “r1” , it will initiate the default constructor and from that “default” constructor will call another constructor with same name but with 4 parameters. Hope you understand the importance of “this” in java. If you have any doubt, ask me in comments.

Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

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