7.4 Writing Constructors

A constructor is a special method that is called when an object is instantiated using the new keyword. A class can have several constructors. The job of the class constructors is to initialize the fields of the new object.

The syntax for a constructor follows:

accessModifier ClassName( parameter list )
{
    // constructor body
}

Notice that a constructor has the same name as the class and has no return type—not even void.

It’s important to use the public access modifier for the constructors so that applications can instantiate objects of the class.

The constructor can either assign default values to the ...

Get Java Illuminated, 5th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.