The Java Constructor Method

Create an Object With a Java Constructor

A Java constructor creates a new instance of an already-defined object. This article discusses how to use Java constructor methods to create a Person object.

Note: You need to create two files in the same folder for this example: Person.java defines the Person class, and PersonExample.java contains the main method that creates Person objects.

The Constructor Method

Let's start by creating a Person class that has four private fields: firstName, lastName, address and username.

These fields are private variables and together their values make up the state of an object. We've also added the simplest of constructor methods:

 public class Person {
 
   private String firstName;
   private String lastName;
   private String address;
   private String username;
 
   //The constructor method
   public Person()
   {
 
   }
 }
 

The constructor method is similar to any other public method except that it shares the same name as the class, and it cannot return a value. It can have none, one or many parameters.

Currently, our constructor method does nothing at all, and it's a good time to consider what this means for the initial state of the Person object. If we left things as they are or we didn't include a constructor method in our Person class (in Java you can define a class without one), then the fields would have no values — and we certainly want our person to have a name and address as well as other characteristics.

 If you think there's a chance that your object might not be used as you expect and the fields might not be initialized when the object is created, always define them with a default value:

 public class Person {
 
   private String firstName = "";
   private String lastName = "";
   private String address = "";
   private String username = "";
 
   //The constructor method
   public Person()
   {
 
   }
 }
 

Normally, to ensure that a constructor method is useful, we would design it to expect parameters. The values passed through these parameters can be used to set the values of the private fields:

 public class Person {
 
   private String firstName;
   private String lastName;
   private String address;
   private String username;
 
   // The constructor method
   public Person(String personFirstname, String personLastName, String personAddress, String personUsername)
   {
     firstName = personFirstName;
     lastName = personLastName;
     address = personAddress;
     username = personUsername;
   }
 
   // A method to display the state of the object to the screen
   public void displayPersonDetails()
   {
     System.out.println("Name: " + firstName + " " + lastName);
     System.out.println("Address: " + address);
     System.out.println("Username: " + username);
   }
 }
 

Our constructor method now expects the values of four strings to be passed to it. They are then used to set the initial state of the object. We've also added a new method called displayPersonDetails() to enable us to see the state of the object after it has been created.

Calling the Constructor Method

Unlike other methods of an object, the constructor method must be called using the "new" keyword:

 public class PersonExample {
 
   public static void main(String[] args) {
 
     Person dave = new Person("Dave", "Davidson", "12 Main St.", "DDavidson");
     dave.displayPersonDetails();
 
   }
 }
 

Here's what we did:

  1. To create the new instance of the Person object, we first define a variable of type Person that will hold the object. In this example, we've called it dave.
  2. On the other side of the equals sign, we call the constructor method of our Person class and pass it four string values. Our constructor method will take those four values and set the initial state of the Person object to be: firstName = "Dave", lastName = "Davidson", address = "12 Main St", username = "DDavidson".

Notice how we've switched to the Java main class to call the Person object. When you work with objects, programs will span multiple .java files.

Make sure you save them in the same folder. To compile and run the program, simply compile and run the Java main class file (i.e., PersonExample.java). The Java compiler is smart enough to realize that you want to compile the Person.java file as well, because it can see that you have used it in the PersonExample class.

Naming of Parameters

The Java compiler gets confused if the parameters of the constructor method have the same names as the private fields. In this example, you can see that we have distinguished between them by prefixing the parameters with the word "person." It's worth mentioning that there is another way. We can use the "this" keyword instead:

   // The constructor method
   public Person(String firstName, String lastName, String address, String username)
   {
     this.firstName = firstName;
     this.lastName = lastName;
     this.address = address;
     this.username = username;
 
   }
 

The "this" keyword tells the Java compiler that the variable to be assigned the value is the one defined by the class, not the parameter. It's a question of programming style, but this method helps us define constructor parameters without having to use multiple names.

More Than One Constructor Method

When designing your object classes, you are not limited to using only one constructor method. You might decide there are a couple of ways an object can be initialized. The only constraint on using more than one constructor method is that the parameters must differ.

Imagine that at the time we create the Person object, we might not know the username. Let's add a new constructor method that sets the state of the Person object using only the firstName, lastName and address:

 public class Person {
 
   private String firstName;
   private String lastName;
   private String address;
   private String username;
 
   // The constructor method
   public Person(String firstName, String lastName, String address, String username)
   {
     this.firstName = firstName;
     this.lastName = lastName;
     this.address = address;
     this.username = username;
   }
 
   // The new constructor method
   public Person(String firstName, String lastName, String address)
   {
     this.firstName = firstName;
     this.lastName = lastName;
     this.address = address;
     this.username = "";
   }
 
   // A method to display the state of the object to the screen
   public void displayPersonDetails()
   {
     System.out.println("Name: " + firstName + " " + lastName);
     System.out.println("Address: " + address);
     System.out.println("Username: " + username);
   }
 }
 

Note that the second constructor method is also called "Person" and it also does not return a value. The only difference between it and the first constructor method is the parameters – this time it expects only three string values: firstName, lastName and address.

We can now create Person objects in two different ways:

 public class PersonExample {
 
   public static void main(String[] args) {
 
     Person dave = new Person("Dave", "Davidson", "12 Main St.", "DDavidson");
     Person jim = new Person("Jim","Davidson", "15 Kings Road");
     dave.displayPersonDetails();
     jim.displayPersonDetails();
   }
 
 }
 

Person dave will be created with a firstName, lastName, address and username. Person jim, however, will not get a username, i.e. the username will be the empty string: username = "".

A Quick Recap

Constructor methods are called only when a new instance of an object is created. They:

  • Must have the same name as the class
  • Do not return a value
  • Can have none, one, or many parameters
  • Can number more than one as long as each constructor method has a different set of parameters
  • Can have parameter names the same as the private fields as long as the "this" keyword is used
  • Are called using the "new" keyword