next up previous
Next: Standard constructor Up: Unit 03 Previous: Invocation of a constructor

Overloading of constructors

Since Java admits overloading of methods, and a constructor is a special case of a method, it is possible to define several constructors for a class.

For example, we can define a constructor that sets to null the residence of persons that are being created.

// constructor name
public Person(String n) {
  name = n;
  residence = null;
}

We show some examples of how to use the constructors:

Person p1 = new Person("John Smith");
                 // calling constructor name
Person p2 = new Person("Tom Jones", "London");
                 // calling constructor name-residence
System.out.println(p1.getName());
                 // prints "John Smith"
System.out.println(p2.getName());
                 // prints "Tom Jones"

When we create an object by means of a new operation, the compiler determines which constructor to use based on the number and the types of parameters specified in the new operation. The run-time support can then call the chosen constructor to create the object.


next up previous
Next: Standard constructor Up: Unit 03 Previous: Invocation of a constructor