How to Use the this Keyword to Call Another Constructor in Java

  • google plus

In Brief...

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.

Instructions

  1. Open your text editor and create a new file that will contain the Person class with two constructors. Type in the following Java statements:
    Java Source for Use this to Call Another Constructor

  2. Two constructors are defined. The second constructor calls the first one to avoid a redundant statement that assigns last name to the input parameter.

  3. Save your file as Person.java.

  4. Open your text editor and create the Java program that will test the Person class. Type in the following Java statements:
    Java Source for Use this Call Another Constructor

  5. Two Person objects are instantiated. The second object is created using the constructor that calls another constructor using this.

  6. Save your file as UsethisToCallAnotherConstructor.java.

  7. 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.
    Compile Use this Call Another Constructor Person

  8. Type in the command to compile the tester class and hit Enter.
    Compile Use this Call Another Constructor

  9. 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.
    Run Use this Call Another Constructor

Related Video

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss