I have a car class and an electric machine class. The fact is that the electric machine class inherits the Fuel field from the machine class and I need to delete or rename it simply because the electric machine does not have fuel but has a charge.

 class Car { public int MaxSpeed = 180; public int Range = 100; public int CurrentSpeed = 100; public int Fuel = 100; public void Drive() { if (Fuel <= 0) throw new Exception("Not enough fuel"); else { this.Fuel--; Range -= Range / CurrentSpeed; } } } class ElectroCar : Car { int Charge; public ElectroCar() { Charge = base.Fuel; } } 
  • And why not make the extra field just private, not sure about C #, but in C ++ this is easily done, then this field will not be available for the descendant class. - Arty OneSoul
  • one
    @ArtyOneSoul: You can do this. That's not the question. The question in the sense of inheritance: the derived class must be a kind of base. An electric car is not a type of car with fuel. - VladD

2 answers 2

No

If the ancestor class has fields that have no meaning in the descendant class, then you have incorrectly built the inheritance hierarchy.

There are different ways to fix the situation. For example: highlight the total from Car and ElectroCar to the base class Vehicle , rename the FuelCar , and the properties related to fuel, let it contain only FuelCar .

  • also thought about it before, thought there was an alternative, thanks! - ishidex2
  • @Duoxx: Please! - VladD
  • @Duoxx, amendment: CarBase , not CarBase . After all, the selected common features can be inherited not only for various types of cars, but also for trolley buses, for example. - окт
  • @Duoxx support Arhad, more correct than Vehicle , then you can also inherit a team with a donkey. - 0xdb
  • And why not to make the Fuel property - Fuel {private get; private set;} Fuel {private get; private set;} ? - Sergey

I suggest adding a Source enumeration.

 enum Sources { Gas, Diesel, Petrol, Kerosene, Electricity } 

Replace the fuel field with the powerSource of the Sources type and add the numeric field powerIndex that characterizes the numeric energy consumption indicator

  • 2
    The idea is good. But the question is, in what units of powerIndex ? And if we have a hybrid machine, you need two powerIndex ? Not, if we go to the composition, make PowerSource full-fledged interface, and let each implementation work in its own way. - VladD