next up previous
Next: Overloading of constructors Up: Unit 03 Previous: Constructors

Invocation of a constructor

A constructor is automatically called by the run-time support (the Java Virtual Machine) when an object is created using the new operator. For example, with the following code fragment

Person p = new Person("John Smith", "London");
                // constructor name-residence is called
System.out.println(p.getResidence());
                // prints "London"
the run-time support calls the constructor Person(String,String), which creates (i.e., allocates the memory for) an object of the class Person and initializes explicitly the fields name and residence to the values passed as parameters. The reference to the newly created object is then assigned to the variable p.

Consider the following code fragment:

Person p;                                // (1)
p = new Person("John Smith", "London");  // (2)

In (1), we define a variable p of type reference to an object of type Person, while in (2) we create a new object Person, and we assign the reference to it to the variable p.

Note: The new operator uses a constructor to create an object, and returns a reference to it. Such a reference can:

Note: It is important that all constructors are declared as public fields of the class. If they were declared private, then any attempt to create an object of the class would generate an error.


next up previous
Next: Overloading of constructors Up: Unit 03 Previous: Constructors