B.6 Initializing Objects with Constructors
As mentioned in Section B.4, when an object of class GradeBook
(Fig. B.5) is created, its instance variable courseName
is initialized to null
by default. What if you want to provide a course name when you create a GradeBook
object? Each class you declare can provide a special method called a constructor that can be used to initialize an object of a class when the object is created. In fact, Java requires a constructor call for every object that’s created. Keyword new
requests memory from the system to store an object, then calls the corresponding class’s constructor to initialize the object. The call is indicated by the parentheses after the class name. A constructor must have the same name as the class. ...
Get Android How to Program, 3/e 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.