Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About C# and Inheritance

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?

like image 850
IssamTP Avatar asked Sep 02 '11 12:09

IssamTP


Video Answer


2 Answers

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:

  • Prefix interfaces with I, IAutomobile.
  • Capital letters on methods: Speedup(), Break(), Steer().
like image 178
Adam Houldsworth Avatar answered Oct 10 '22 20:10

Adam Houldsworth


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();
    }
}
like image 42
as-cii Avatar answered Oct 10 '22 19:10

as-cii