Home >Java >javaTutorial >Adding a Constructor to the Vehicle Class

Adding a Constructor to the Vehicle Class

WBOY
WBOYOriginal
2024-07-28 07:24:53376browse

Adicionando um Construtor à Classe Vehicle

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn