I have below code with IVehicle
interface having TestDrive
method.
There is an abstract class - Vehicles
, which implements IVehicle
& has a property TestDriveTime
.
There are a number of child classes like Car
, Scooter
, etc (about 25 such child classes). which derive from Vehicle
& have their own implementations of TestDrive()
.
Please help me with my questions -
TestDrive
sequentially, is my code in Main()
correct?TestDriveTime
, how shall I set it?.
public interface IVehicle
{
void TestDrive();
}
public abstract class Vehicle : IVehicle
{
public DateTime TestDriveTime { get; set; }
abstract public void TestDrive();
}
public class Car : Vehicle
{
public override void TestDrive()
{
// code for car testDrive
// uses TestDriveTime
}
}
public class Scooter : Vehicle
{
public override void TestDrive()
{
// code for car testDrive
// uses TestDriveTime same as car
}
}
static void Main(string[] args)
{
IVehicle vehicle = null;
// 1. need to set the TestDriveTime which can be used for vehicles of all types.
vehicle = new Car();
vehicle.TestDrive();
// 2. Need to run the TestDrive for all vehicles sequentially
vehicle = new Scooter();
vehicle.TestDrive();
}
1) Declare a list:
List<IVehicle> vehicles = new List<IVehicle>();
then add all of your vehicles:
vehicles.Add(new Car());
vehicles.Add(new Scooter());
and iterate:
foreach (IVehicle v in vehicles)
v.TestDrive();
2) You can set TestDriveTime and use it for all of your objects:
v.TestDrive(TestDriveTime);
Change the method declaration to: IVehicle.TestDrive(DateTime testDriveTime)