a real-world example question that involves both method overloading and method overriding in Java:
You are tasked with developing a simple vehicle management system for a vehicle rental company. The system needs to manage different types of vehicles and calculate rental costs based on the type and rental duration. You need to implement the following:
-
Vehicle Class:
- A base class
Vehicle
with attributesmake
,model
, andyear
. - A method
getRentalCost(int days)
to calculate the rental cost.
- A base class
-
Car and Bike Classes:
- Two derived classes
Car
andBike
that inherit fromVehicle
. - Override the
getRentalCost(int days)
method to provide specific rental cost calculations for cars and bikes.
- Two derived classes
-
Rental Cost Calculation:
- The base
Vehicle
class should provide a default rental cost calculation. - The
Car
class should charge a flat rate per day plus an additional fee for each day. - The
Bike
class should charge a flat rate per day with no additional fees.
- The base
-
Method Overloading:
- Overload the
getRentalCost
method in theVehicle
class to allow calculating the rental cost for both days and hours. The methodgetRentalCost(int days, int hours)
should calculate the cost by converting hours to a fraction of a day.
- Overload the
-
Vehicle Class:
- Attributes:
make
(String),model
(String),year
(int). - Methods:
getRentalCost(int days)
: Returns the rental cost for the given number of days.getRentalCost(int days, int hours)
: Returns the rental cost for the given number of days and hours.
- Attributes:
-
Car Class:
- Inherits from
Vehicle
. - Overrides
getRentalCost(int days)
to charge $50 per day plus $20 additional fee for each day.
- Inherits from
-
Bike Class:
- Inherits from
Vehicle
. - Overrides
getRentalCost(int days)
to charge $20 per day with no additional fees.
- Inherits from
-
Main Program:
- Create instances of
Car
andBike
. - Demonstrate method overloading and overriding by calculating rental costs for different durations.
- Create instances of
Car Rental for 3 days: $210
Car Rental for 2 days and 12 hours: $180
Bike Rental for 3 days: $60
Bike Rental for 2 days and 12 hours: $50
-
Method Overloading:
- The
getRentalCost(int days)
method is overloaded with another methodgetRentalCost(int days, int hours)
in theVehicle
class to handle both days and hours.
- The
-
Method Overriding:
- The
Car
andBike
classes override thegetRentalCost(int days)
method from theVehicle
class to provide specific rental cost calculations.
- The
This example allows you to demonstrate understanding and implementation of both method overloading and overriding in a practical scenario.
SELF TRY - LEARN JAVA - Q2