6.1 Constructors

First things first.


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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.