c# abstract classes

2019-05-31 06:32发布

i have to create a fake DMV program that calculates annual fees, for commercial and private vehicles. Those two classes will be abstract and they will polymophism from a class named all vehicles.

My instructor wants only one object created the entire program(in main) but since my top 3 tier classes are abstract. I can't create an object with them i.e. vehicles = new vehicles();

so my question is how do i create only one object since they are abstract? If you have any questions feel free to ask, I might have not explained this well...

4条回答
劫难
2楼-- · 2019-05-31 06:49

Your class structure will look something like:

abstract class Vehicle
{
    protected abstract int BaseFee { get; }
    protected abstract int ExtraFee { get; }

    public int CalculateFee()
    {
        return BaseFee + ExtraFee;
    }
}

abstract class CommercialVehicle : Vehicle
{
    protected override int BaseFee
    {
        return 100;
    }
}

class LightDutyTruck : CommercialVehicle
{
    protected override int ExtraFee
    {
        return 50;
    }
}

class Semi : CommercialVehicle
{
    protected override int ExtraFee
    {
        return 150;
    }
}

[etc...]

abstract class PrivateVehicle : Vehicle
{
    protected override int BaseFee
    {
        return 25;
    }
}

class Sedan : PrivateVehicle
{
    protected override int ExtraFee
    {
        return 15;
    }
}

and so on, for each class. In your Main method, you would create the instance based on input, but your actual variable would be declared as type Vehicle. The actual calculation will take effect based on the instance that you create:

Vehicle v;
switch(input)
{
    case "semi":
        v = new Semi();
        break;
    case "truck":
        v = new LightDutyTruck();
        break;
    ...
}

int fee = v.CalculateFee();
查看更多
萌系小妹纸
3楼-- · 2019-05-31 06:49

Your instructor may want you to instantiate multiple objects through a reference to the abstract base class:

Vehicle conveyance;
conveyance = new PrivateVehcicle();
conveyance.Drive();
conveyance.Stop();
// or whatever ...
conveyance = new CommercialVehcicle();
conveyance.Drive();
conveyance.Stop();

i.e. you have a single object reference (conveyance) that behaves polymorphically depending on the concrete type you've instantiated.

查看更多
Explosion°爆炸
4楼-- · 2019-05-31 06:57

Maybe you are to make one object which represents the DMV, but the definition of that object includes instances of other objects.

class DMV {
 private List<Vehicle> vehicles = new List<Vehicle>();
 ...
}
查看更多
啃猪蹄的小仙女
5楼-- · 2019-05-31 06:59

You seem to be a bit confused. "All Vehicles" should be abstract. "Commercial Vehicle" and "Private Vehicle" should not be abstract, unless there are concrete subclasses of those two.

You may also not be understanding what your instructor means by "only one object", since that doesn't make sense.

查看更多
登录 后发表回答