Calling a Constructor from a Constructor
In this lesson, we look at how one constructor can call another constructor and why you would want to do so.
We'll cover the following
The class Name
As we know, a class can define several constructors. Such constructors have different parameters but perform similar initializations of the class’s data fields. For example, the class Name
has two constructors and begins as follows:
public class Name
{
private String first; // First name
private String last; // Last name
public Name()
{
first = ""; // Empty string
last = "";
} // End default constructor
public Name(String firstName, String lastName)
{
first = firstName;
last = lastName;
} // End constructor
.
.
.
Although these two constructors perform simple and brief initializations, the actions are in fact repetitive. When several constructors or methods perform the same task, debugging or modifying the code becomes more difficult.
We have two ways to avoid this duplication of effort, one familiar and one new.
Get hands-on with 1400+ tech skills courses.