Home >Java >javaTutorial >Adding a Constructor to the Vehicle Class
Objective:
Improve the Vehicle class by adding a constructor that automatically initializes the passengers, fuelcap, and mpg fields.
Builder Implementation:
A constructor has been added to the Vehicle class to initialize the mentioned fields when an object is created.
The constructor has three parameters: p for passengers, f for fuelcap, and m for mpg.
Constructor Definition:
The Vehicle(int p, int f, int m) constructor initializes the fields:
Vehicle(int p, int f, int m) { passengers = p; fuelcap = f; mpg = m; }
Class Methods:
range(): Calculates and returns the vehicle's range (miles it can travel on a full tank).
fuelneeded(int miles): Calculates and returns the amount of fuel needed to cover a given distance.
Adjust the use of the classes they use, removing the initialization of attributes in the main method and passing arguments to the constructor of the Vehicle class.
Ex:
Vehicle minivan = new Vehicle(7,16,21);
Vehicle sportscar = new Vehicle(2,14,12);
The above is the detailed content of Adding a Constructor to the Vehicle Class. For more information, please follow other related articles on the PHP Chinese website!