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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.