Java Keywords (Part XV): The many uses of the this keyword

We are up to 39 keywords covered in previous articles! That's 81% keywords covered. We have only 9 keywords to cover and I will be covering 1 of those in this article. We are almost done with all the basic keywords. This article will illustrate the use of the keyword this. I suggest you start with Java Keywords (Part I) before proceeding further, if you have not read any of the previous articles in the Java Keyword series. Also, go back and read the one about Data Types. All of these articles are from September 2018. That should help you find them quickly. You can also use the "search" option at the top of this page. The series was written with natural progression in mind. Therefore, some of the keywords already covered may be used in code examples illustrated here.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.

Using this() to chain constructor calls


public class MyClass {
	public MyClass() {
        System.out.println("From no-arg constructor");
    }
	public MyClass(String s) {
    	this();
        System.out.println("From one-arg constructor");
    }
}
If the above code is executed calling out the one-argument constructor, it will print out "From no-arg constructor" first and then "From one-arg constructor" last. That should not be a surprise because this() appears before the System.out.println() call. When using this to invoke a call to another constructor in the class, it must be the very first line inside the constructor. Otherwise, it will result in a compiling error. Using this to call another constructor in the class is called explicit constructor invocation.

The second thing to know is that you can call this() with arguments so long there is a constructor in the class that has the same number and type of arguments. Typically, your no-argument constructor is the base constructor. Meaning that the no-argument constructor will not include a call to another constructor using this. Two constructors calling each other using this will result in an endless recursive call. Fortunately, the compiler will not allow it; therefore resulting in a compiler error.

Using this() to reference variables


public class MyClass {
	private String name;
	public MyClass(String name) {
    	this.name = name;
    }
}
You might have seen this already in some other article in this series. But, in case you haven't and you don't understand it, the use of the keyword this is to break ambiguation between the local variable (the one being passed in the method), and the global variable with the same name. It is often explained that fields (variables) using the keyword this are the ones that belong to the instance being constructed.

Using this to reference the object itself

This is perhaps the least used and, in my opinion, not recommended in most cases. Consider the following example:

public class MyClass {
	private String s = "bar";
	
	public static void main(String[] args) {
		MyClass cc1 = new MyClass();
		MyClass cc2 = cc1.someMethod();
		cc1.setS("foo"); // What will this do to object cc2?
		System.out.println(cc1.equals(cc2));
	}
	public void setS(String s) {
		this.s = s;
	}
	public MyClass someMethod() {
		return this; // You must understand the impact
	}
}
If this code is executed, it will print out true 100% of the time. The reason is very simple. The method someMethod() returns itself. Please understand that I did not mean a copy of itself. The object cc1 is returning the address of itself to object cc2. Because both objects are pointing to the same address in memory, changes made to one object automatically affect the other. Most of the time, creating duplicate objects in this manner is wasteful and unnecessary. But, the language allows it becuase they might be some situations when this is warranted. It is up to you to decide. But, as many other things in software development, make sure you understand the impact of what you are going to do before you do it.

I hope this was of some benefit to you. Next up, is using the keyword super.

Next up, Part XVI: The many uses of the super keyword

Comments

Popular posts from this blog

Implementing Interfaces with Java Records

Customizing Java Records

Exception Handling: File CRUD Operations Example