1. Computing

The Constructor Method

By

The constructor method is called when a new instance of an object is created. Using the example of a Person object I'll be discussing how to create constructor methods in Java.

Example Note: You will need to create two files in the same folder for this example; Person.java contains the Person class, and PersonExample.java is the main Java class (i.e., it 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. I'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 like a normal 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 the 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. 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 for a constructor method to be useful we would design it so that it expects 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 constructer method now expect the values of four strings to be passed to it. They are then used to set the initial state of the object. I'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 Pall Mall", "DDavidson");
     dave.displayPersonDetails();
 
   }
 }
 

To create the new instance of the Person object we first define a variable of type Person that will hold the object. In the example I've called it dave. On the other side of the equals sign we are calling the constructor method of our Person class and passing it four string values. Our constructor method will takes those four values and set the initial state of the Person object to be: firstname = "Dave", lastname = "Davidson", address = "12 Pall Mall", username = "DDavidson".

Notice how I've switched to the Java main class to call the Person object. When you work with objects you will have programs that span multiple .java files. Make sure you save them in the same folder. To compile and run the program nothing has changed, 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 will get confused if the parameters of the constructor method have the same names as the private fields. In the example you can see that I 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 is my preferred method of defining constructor parameters because it's easier than thinking up new names!

Continue on to the next page to learn about multiple constructor methods.

©2014 About.com. All rights reserved.