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

Constructors

With what we have seen till now we have no means to initialize with a suitable value the field name of a Person object. We do not know how to let an object correspond, e.g., to John Smith. The instance variable name should have the value "John Smith", but this variables is private, and hence the following statement would be wrong:

Person p = new Person();
p.name = "John Smith";   // ERROR! name is declared private

To make it possible to explicitly initialize private instance variables of objects, we have to use constructors. A constructor is simply a (non static) method of a class that has the same name as the class and does not have an explicit return value (not even void).

For example, let us realize a constructor for the class Person that takes as arguments the name and the residence of the person to create.

public class Person {
  ...
  // constructor name-residence
  public Person(String n, String r) {
    name = n;
    residence = r;
  }
  ...
}


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