"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Adding a Constructor to the Vehicle Class

Adding a Constructor to the Vehicle Class

Published on 2024-07-30
Browse:703

Adicionando um Construtor à Classe Vehicle

Goal:
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);

Release Statement This article is reproduced at: https://dev.to/devsjavagirls/adicionando-um-construtor-a-classe-vehicle-1dea?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3