How to Use the this Keyword to Call Another Constructor in Java
A Java class may have more than one constructor. Usually the assignments made in each constructor overlap. To eliminate redundant assignment statements, the developer can call another constructor by using the
this keyword. To write a program that uses
this in this manner, follow these seven steps.
- Open your text editor and create a new file that will contain the Person class with two constructors. Type in the following Java statements:
- Save your file as Person.java.
- Open your text editor and create the Java program that will test the Person class. Type in the following Java statements:
- Save your file as UsethisToCallAnotherConstructor.java.
- Open a command prompt and navigate to the directory containing your Java programs. Then type in the command to compile the Person source and hit Enter.
- Type in the command to compile the tester class and hit Enter.
- You are ready test your Person class. Type in the command to run the Java runtime launcher and hit Enter. Notice the second line of output displaying last name, indicating the second constructor successfully called the first constructor.
Two constructors are defined. The second constructor calls the first one to avoid a redundant statement that assigns last name to the input parameter.
Two Person objects are instantiated. The second object is created using the constructor that calls another constructor using