Aqua Phoenix
     >>  Lectures >>  Java 2  
 

Navigator
   
 
       
   

2.3 Constructor

A constructor is a special method that is invoked when an object is first created. It is accessed only once per object and never again after the object has been instantiated. It is used to set the objects initial state.

public class Person {

  public Person() {
  }
}
Rules and Observations
  • The constructor is named after the class it appears in.
  • A constructor must be public, otherwise it cannot be used from outside the class.
  • Constructors have no return type or value. They are used to instantiate a class and are not meant to return values.
  • If a class does not explicitely define a constructor, the the default constructor applies. The default constructor takes no arguments and has no explicit code to initialize variables, etc. The constructor above is an example of a default constructor.

Going back to the example of class Person, we have not defined a constructor. While we can dispense with using methods for setting names and age, we recognize a problem with the class:

public class PersonTest {

  public static void main(String[] args) {

    Person john = new Person();
    john.printInfo();
  }
}
In this example, we make no use of methods in class Person, and thus neither variable name nor variable age are set to any values. The output is thus:

Name: null, Age: 0
Objects (e.g. String) are by default initialized to null. Integers and other numerical data types are initialized to 0. Glancing over the code from within class Person, we observe the following:

  private String name;
  private int age;
While both variables are properly declared, they have not been initialized to any default values. For that reason, the information printed upon calling method printInfo() refers to uninitialized values.

It is good practice to supply a constructor for every class in which variables are set to default values. We extend the original class Person by adding a default constructor:

public class Person {

  private String name;
  private int age;


  public Person() {

    name = "";
    age = 0;
  }

  ...
}
With this constructor, all member variables in class Person are initialized, and every new object of class Person will by default contain an empty name and an age of 0. Repeating the example from above we find a more controlled behavior:

public class PersonTest {

  public static void main(String[] args) {

    Person john = new Person();
    john.printInfo();
  }
}
Output:

Name: , Age: 0
Constructors can also be used to force new objects of a class to be created with specific values. In our example this would be useful so that no empty person exists. Other than for the lack of a return type, constructors behave similar to methods, and can be passed parameters:

public class Person {

  private String name;
  private int age;


  public Person(String n, int a) {

    name = n;
    age = a;
  }

  ...
}
This constructor prohibits an object of class Person to be created without passing some parameters to define the values of name and age. The test code changes accordingly:

public class PersonTest {

  public static void main(String[] args) {

    Person john = new Person("John", 20);
    Person mike = new Person("Mike", 25);

    john.printInfo();
    mike.printInfo();
  }
}
This test case is much more succinct than before, since it combines the declaration of the object with the definition of member variables. However, the passed parameters are not tested against incorrect ranges, i.e. if a negative age is set using the constructor, then the value of age in the object is in fact negative. As we have done for method setAge(), we can test the values and set other defaults if necessary. This can be accomplished by including code in the constructor or by calling appropriate methods.

In our above example:

public class Person {

  private String name;
  private int age;


  public Person(String n, int a) {

    if (a < 0) {
      age = 0;
    } else {
      age = a;
    }

    name = n;
  }

  ...
}
is equivalent to:

public class Person {

  private String name;
  private int age;


  public Person(String n, int a) {

    setName(n);
    setAge(a);
  }

  ...
}