3.4 Account Class: Initializing Objects with Constructors

As mentioned in Section 3.2, when an object of class Account (Fig. 3.1) is created, its String instance variable name is initialized to null by default. But what if you want to provide a name when you create an Account object?

Each class you declare can optionally provide a constructor with parameters that can be used to initialize an object of a class when the object is created. Java requires a constructor call for every object that’s created, so this is the ideal point to initialize an object’s instance variables. The next example enhances class Account (Fig. 3.5) with a constructor that can receive a name and use it to initialize instance variable name when an Account object is created ...

Get Java™ How To Program (Early Objects), Tenth 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.