Say that we wanted to make one more vehicle that operates a bit differently than a sedan or truck. We want to use most of the members in
Vehicle, but we need to write new versions of
What we want is to override an inherited method. To do that, we use the
In the superclass, we mark the method in question as
virtual, which tells the computer “this member might be overridden in subclasses”:
public virtual void SpeedUp()
In the subclass, we mark the method as
override, which tells the computer “I know this member is defined in the superclass, but I’d like to override it with this method”:
public override void SpeedUp()
As an aside: there’s another way to solve this problem. Instead of using
override to override a member, we can define a
new member with the same name. Essentially, the inherited member still exists, but it is “hidden” by the member in the subclass. If this sounds confusing, that’s okay! We also think it leads to unnecessary confusion, and that leads to errors. We’re going to stick with the
override approach in this lesson.
Bicycle class will access the
Speed properties in
Vehicle, so make both setters
protected again in Vehicle.cs.
Wheels should already be protected — we set that a few exercises ago.
In Bicycle.cs, create an empty
Bicycle class that inherits
Define a constructor that:
- has one
doubleparameter for setting the
base()with that parameter
- in its body, sets
public void SpeedUp() method that limits the
15. In other words, in the method body:
Speedis greater than
15, set it to
An error might occur here, which is okay.
You probably saw the warning:
warning CS0108: 'Bicycle.SpeedUp()' hides inherited member 'Vehicle.SpeedUp()'. Use the new keyword if hiding was intended.
The computer suggests using the
new approach, but we prefer
override for its clarity.
In Bicycle.cs, label
Now your probably saw the error:
error CS0506: 'Bicycle.SpeedUp()': cannot override inherited member 'Vehicle.SpeedUp()' because it is not marked virtual, abstract, or override
In Vehicle.cs, label
Repeat the process with
SlowDown() in Bicycle.cs (let’s assume that only sedans and trucks can go in reverse). It should override the inherited version and limit the
Speed to 0. In other words, the method:
- Sets it to
Speedis less than
- Is labeled
In Vehicle.cs, label