6.1 Constructors

First things first.

—COMMON SAYING

When you create an object of a class using the new operator, you invoke a special kind of method called a constructor. At that time, you often want certain initializing actions to occur, such as giving specific values to the instance variables. A constructor will perform such initializations. In this section, we tell you how to define and use constructors.

Defining Constructors

A constructor is a special method that is called when you use the new operator to create a new object. Until now, Java has supplied a constructor for us. For example, given the class Species in Listing 5.19 of the previous chapter, we can create a new Species object by writing ...

Get Java: An Introduction to Problem Solving and Programming, 8th 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.