Imagine a rental company that has cars for the company to use internally and trucks to rent. The cars use gas and the trucks use diesel. The trucks have additional things that they do that cars do not - they are rented. So I have the following code:
abstract class Vehicle
{
public abstract FuelType Fuel();
}
class Car : Vehicle
{
public override FuelType Fuel()
{
return FuelType.Gas;
}
}
class Truck : Vehicle
{
public override FuelType Fuel()
{
return FuelType.Diesel;
}
//Not in base class or Car class
public List<Rental> Rentals()
{
return new List<Rental>();
}
}
class Rental
{
//...some stuff here
}
enum FuelType
{
Gas,
Diesel
}
What is normally done when the child classes have additional methods and properties? Example:
List<Vehicle> vehicles = new List<Vehicle>() { };
vehicles.Add(new Car());
vehicles.Add(new Truck());
foreach (var vehicle in vehicles)
{
Console.WriteLine(vehicle.Fuel().ToString());
//Pseudocode here:
if(vehicle.GetType() is Truck)
{
//Provide rental information
Truck truck = (Truck)vehicle;
truck.ProvideSomeInfo();
}
}
I get how polymorphism works when you have classes that have all the same methods, properties, fields, etc. What is normally done when you need to work with the base class AND you need to work with additional methods, fields, properties that all the children do not share?
All the abstract tutorials that I have found just show the simpler case when all the children have the same sets of methods, properties, fields.