When we treat sub-class method as an overriding method?
We treat a subclass method as an overriding method when it meets the following criteria:
-
Inheritance: The subclass must inherit from a base class that has a method with the same name and signature. In other words, the subclass must be derived from the base class that declares the method.
-
Method Signature: The overriding method in the subclass must have the same name, return type, and parameters (including the order and types of the parameters) as the method in the base class.
-
Override Keyword: The overriding method in the subclass must be explicitly marked with the override keyword to indicate that it is intended to override a method from the base class. This keyword ensures that the method is correctly overridden and provides compile-time checks.
Here's an example that demonstrates the overriding of a method in a subclass:
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape.");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
In the above example, the Shape class has a virtual method Draw(), and the Circle class inherits from Shape. The Circle class overrides the Draw() method by providing its own implementation.
By using the override keyword in the Draw() method of the Circle class, we explicitly indicate that this method is intended to override the Draw() method of the Shape class. This enables polymorphism, so when we call the Draw() method on an instance of the Circle class, the overridden implementation in the Circle class is executed instead of the base implementation in the Shape class.
Shape shape = new Circle();
shape.Draw(); // Output: Drawing a circle.
In the above code, we create an instance of the Circle class and assign it to a variable of type Shape. When we call the Draw() method on this instance, the overridden method in the Circle class is invoked, resulting in the output "Drawing a circle."