I have a theorical/pratical question about how inheritance works in C#.
Let's say that I have to model some autos, so I have a few common methods that all the autos must implement and a pilot should know. In code-words this should be an Interface:
interface Automobile {
void speedup();
void break();
void steer();
//bla bla
}
Now, all kind of car should have some common technical implementations beside the actions that a pilot can perform over them, let's say the property fuelLevel, at this point I still don't want to know how a car speeds up or breaks down, so I would wrote:
abstract class Car : Automobile {
int fuelLevel; // for example....
public abstract void speedup();
public abstract void break();
public abstract void steer();
}
Now I want to model a Ferrari, so:
class Ferrari : Car {
public void speedup() { ... }
public void break() { ... }
public void steer() { ... }
}
Now, in Java this code should work (changing some syntax), but in C# won't because it says:
Error 1 'Ferrari' does not implement inherited abstract member 'Car.speedup()'
Error 1 'Ferrari' does not implement inherited abstract member 'Car.break()'
Error 1 'Ferrari' does not implement inherited abstract member 'Car.steer()'
Why? How should I fix this problem?
You need to mark the methods with override
to cover the abstract
definitions beneath:
class Ferrari : Car
{
public override void speedup() { }
public override void break() { }
public override void steer() { }
}
Other than that, you're set - the Ferrari
class will satisfy your interface, even though the methods are derived. Also as an aside, naming in C# is slightly different:
I
, IAutomobile
.Speedup()
, Break()
, Steer()
.You are actually ignoring to override abstract class members. Try to consider something like:
interface IAutomobile
{
void Steer();
void Break();
}
abstract class Car : IAutomobile
{
public abstract void Steer();
public abstract void Break();
}
class Ferrari : Car
{
public override void Steer()
{
throw new NotImplementedException();
}
public override void Break()
{
throw new NotImplementedException();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With