Constructor Methods

You also can define constructor methods in your class definition that are called automatically when objects of that class are created.

A constructor method is a method that is called on an object when it is created—in other words, when it is constructed.

Unlike other methods, a constructor cannot be called directly. Java does three things when new is used to create an instance of a class:

  • Allocates memory for the object

  • Initializes that object's instance variables, either to initial values or to a default (0 for numbers, null for objects, false for Booleans, or '\ 0' for characters)

  • Calls the constructor method of the class, which might be one of several methods

If a class doesn't have any constructor methods defined, an object ...

Get Sams Teach Yourself Java 2 in 21 Days, 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.