Method Overriding
Method overriding is when a child class does an inherited job its own way, like a kid who cooks Grandma's recipe with a twist. The parent has to say the method may be changed with the virtual word.
In this page:
Syntax
class BaseClass
{
public virtual ReturnType MethodName() { }
}
class DerivedClass : BaseClass
{
public override ReturnType MethodName() { }
}
Method Overriding
A base class marks a method virtual to allow derived classes to replace its behavior with override.
At runtime, C# calls the overridden version based on the object's actual type, not the variable's declared type — this is polymorphism. Without virtual/override, a derived method with the same name just hides the base one instead.
Warning:
Forgetting
virtual on the base method means override in the derived class will not compile.Example: Method Overriding
using System;
class Shape
{
public virtual double Area()
{
return 0;
}
}
class Circle : Shape
{
public double Radius;
public Circle(double radius)
{
Radius = radius;
}
public override double Area()
{
return Math.PI * Radius * Radius;
}
}
class Program
{
static void Main(string[] args)
{
Shape s = new Circle(3);
Console.WriteLine(s.Area());
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting
virtualin the base method, sooverrideis not allowed. - Forgetting
overridein the derived method, which creates a hiding warning instead of overriding. - Changing the return type or parameters of an overriding method, which is a compile error.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: