I learned how to inherit methods by adding virtual
to the method in the base class and override
in the new class. But what do I do to inherit properties?
class bird
{
private virtual string fly = "Yes, I can!";
public string CanI() { return fly ; }
}
class penguin : bird
{
private override string fly = "No, I can't!";
}
This pops an error, saying that modifiers virtual
/override
should not be used here.
fly
is not a property, it is a field. Fields are not overrideable. You can do this:
class bird {
protected virtual string Fly {
get {
return "Yes, I can!";
}
}
public string CanI() { return Fly; }
}
class penguin : bird {
protected override string Fly {
get {
return "No, I can't!";
}
}
}
Note that I had to mark fly
as protected
.
But even better, I would do something like this:
abstract class Bird {
public abstract bool CanFly { get; }
public string SayCanFly() {
if(CanFly) {
return "Yes, I can!";
}
else {
return "No, I can't!";
}
}
}
class Penguin : Bird {
public override bool CanFly {
get {
return false;
}
}
}
class Eagle : Bird {
public override bool CanFly {
get {
return true;
}
}
}
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