Java basic- Overview - Viết chương trình quản lý xe car bằng java
1. Create an interface named ICar
Define an interface called ICar that declares the following methods:
-
calculateTax()→ returns afloat:
Used to calculate the tax of the car. -
calculatePrice()→ returns afloat:
Used to calculate the total cost (total price) of the car. -
getInfo()→ returnsvoid:
Used to display the information of the car.
2. Create a class Car that implements the ICar interface
The Car class should implement all methods from ICar.
Declare the following private fields:
Requirements:
-
Create two constructors:
-
A default (no-argument) constructor.
-
A parameterized constructor that initializes all attributes.
-
-
Generate getters and setters for all fields.
Implement methods:
-
calculateTax()
Calculate the tax based on the number of seats:-
If the car has fewer than 7 seats, then
tax = rootPrice * 0.6 -
Otherwise,
tax = rootPrice * 0.7
-
-
calculatePrice()
Calculate the total price as:
totalPrice = rootPrice + tax -
getInfo()
Display the car’s details in the following format:Example:
Ford car produced by Ford in 1997 has 4 seats with the total price of 20000 $.
3. Create a class LuxuryCar that extends the Car class
Add one new private attribute:
Requirements:
-
Create two constructors:
-
A default constructor.
-
A parameterized constructor (including inherited attributes and
specialRate).
-
-
Create getters and setters for
specialRate.
Override and overload methods:
-
Override
calculatePrice()
Calculate the total price as:
totalPrice = rootPrice + tax + (rootPrice * specialRate) -
Overload
calculatePrice(float transportCost)
Add one parameter namedtransportCost(typefloat), and calculate:
totalPrice = rootPrice + tax + (rootPrice * specialRate) + transportCost
4. Create a Test class
In the main() method:
-
Declare and initialize an instance of
LuxuryCarnamedmyLuxuryCar. -
Input data from the keyboard:
Read values forname,producer,year,seat, androotPrice.-
Use exception handling (
try-catch) to catch invalid inputs.
-
-
Display the car’s information using the
getInfo()method. -
Calculate the total price when the
transportCostis $20,000 using the overloadedcalculatePrice(float transportCost)method. -
Display the final total price.
✅ Summary:
This exercise helps you practice:
-
Defining and implementing interfaces in Java.
-
Using inheritance and method overriding/overloading.
-
Working with constructors, encapsulation (private fields, getters/setters).
-
Handling user input and exceptions.
-
Calculating and displaying object data clearly and logically.