virtual and override
Learn to redefine methods with virtual and override.
virtual methods
A virtual method can be rewritten (overridden) in a derived class. The base class offers a default implementation; a subclass may provide its own: public virtual string Sound() { return "..."; }.
The virtual keyword tells the method 'this behavior can change'. A call looks at the runtime type of the object, not the compile-time type of the variable. This is called polymorphism.
override
The derived class rewrites a virtual method of the base class with override: public override string Sound() { return "Woof"; }.
The signature (name, parameters, return type) must match exactly. Redefining without override shadows with new and does not provide polymorphism. For correct behavior use the virtual + override pair. So Animal a = new Dog(); a.Sound(); runs Dog.Sound.
Exercise Override with Shape and Circle
Define a Shape base class with a public virtual double Area() method (body: return 0;). Then declare class Circle : Shape with public double Radius { get; set; } and public override double Area() (body: return 3.14 * Radius * Radius;). Inside Main create Circle c = new Circle { Radius = 2 }; and print Area().
Show example solution
Shape with override Area. In Main write Circle c = new Circle { Radius = 2 }; Console.WriteLine(c.Area());
Example solution:
using System;
class Shape
{
public virtual double Area()
{
return 0;
}
}
class Circle : Shape
{
public double Radius { get; set; }
public override double Area()
{
return 3.14 * Radius * Radius;
}
}
class Program
{
static void Main()
{
Circle c = new Circle { Radius = 2 };
Console.WriteLine(c.Area());
}
}
Test yourself
-
Match each keyword to its role
- virtual
- Can be overridden
- override
- Overrides
- base
- Base class
- class
- Class definition
-
Complete the override declaration
public ____ string Sound() { return "Woof"; }Show answer
public override string Sound() { return "Woof"; } -
Animal a = new Dog(); a.Sound(); runs what?
// Animal.Sound virtual, Dog.Sound override- Animal.Sound
- Method does not run
- Dog.Sound
- Compile error
Show answer
Dog.Sound — Correct. The runtime type is Dog, so Dog.Sound runs.