4.4. Constructors

The main purpose of constructors is to set the initial state of an object when the object is created by using the new operator.

A constructor has the following general syntax:

<accessibility modifier> <class name> (<formal parameter list>)            <throws clause> // Constructor header  { // Constructor body    <local variable declarations>    <nested local class declarations>    <statements>  }

Constructor declarations are very much like method declarations. However, the following restrictions on constructors should be noted:

  • Modifiers other than an accessibility modifier are not permitted in the constructor header. Accessibility modifiers for constructors are discussed in Section 4.7 on page 131.

  • Constructors cannot return ...

Get Programmer's Guide to Java™ Certification, A: A Comprehensive Primer, Second 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.