Adding a Constructor to the Vehicle Class

We can improve the Vehicle class by adding a constructor that automatically initializes the passengers, fuelcap, and mpg fields when an object is constructed. Pay special attention to how Vehicle objects are created.

Image

Image

Both minivan and sportscar are initialized by the Vehicle( ) constructor when they are created. Each object is initialized as specified in the parameters to its constructor. For example, in the following line,

the values 7, 16, and 21 are passed to the Vehicle( ) constructor when new creates ...

Get Java, A Beginner's Guide, 5th Edition, 5th 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.