Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some trouble with private abstract methods

Let's say I make a major class Car - and I want this class to be abstract. Abstract because this is my major class, nobody should make an object of this class. This class should be only there as "backbone".

I want that classes can be created only from subclasses of Car (lets say Mercedes, Ferrari...). Because every car should have methods like StartEngine I put it into the major class. Let's say I have this:

abstract class Car
{
  public string Name { get; set; }

  public abstract void StartEngine();
  private abstract bool CheckGasoline();
  //and so on...
}

class Mercedes : Car
{
  private override bool CheckGasoline()
  {
  //somehow check gasoline and return whatever...
  }

  public override void StartEngine()
  {
    if (CheckGasoline())
      //start engine...
  }
}

Well this is not gonna work. Because of private abstract:

virtual or abstract members cannot be private

So ill make every private method to protected:

abstract class Car
{
  public string Name { get; set; }

  public abstract void StartEngine();
  protected abstract bool CheckGasoline();
  //and so on...
}

class Mercedes : Car
{
  protected override bool CheckGasoline()
  {
  //somehow check gasoline and return whatever...
  }

  public override void StartEngine()
  {
    if (CheckGasoline())
      //start engine...
  }
}

Is this alright? I mean it's working, but is that how it should be? Using protected when I just need a method in the same class (like here: CheckGasoline() is only needed for StartEngine() ). Somehow private would look better.

Any suggestions? Thank you.

like image 325
miri Avatar asked Aug 12 '12 21:08

miri


1 Answers

Yes that is fine. A sub-type cannot see private methods, therefore cannot override them: they must be protected (or public etc). There is no such thing as "private to method X" in c#, so it'll have to suffice as-is.

like image 89
Marc Gravell Avatar answered Sep 24 '22 06:09

Marc Gravell