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.
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.
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