7.3. Constructors and the “this” Reference

A class constructor is a special routine used to build an object. A constructor is called when you use new ClassName(...) to build an instance of a class. Constructors are defined similarly to an ordinary public method, except that the name must match the class name and no return type is given. Note that if you include a return type (e.g., public void Ship2(...) {...}), the class will compile without warning on most Java systems, but your constructor will not be called when you try to invoke it.

Core Warning

Be sure your constructor does not specify a return type.

You can define constructors with any number ...

Get Core Web Programming, 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.