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

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