Can we execute parent class method if it is overridden in the child class?
When we provide a new implementation for a virtual method from the parent class in the child class, the instance of the child class invokes its own method rather than invoking the method of its parent class.
But yes, you can execute the parent class method even if it's overridden in the child class. This is accomplished by using the 'base' keyword in C#. The 'base' keyword allows you to access members (methods, properties, fields, etc.) of the base class, even when they are overridden in the derived class.
Here's an example illustrating how to use the base keyword to call the parent class method from within the overridden method in the child class:
using System;
class Parent {
public virtual void SomeMethod() {
Console.WriteLine("Parent class method");
}
}
class Child : Parent {
public override void SomeMethod() {
Console.WriteLine("Child class method");
// Call the parent class method using the base keyword
base.SomeMethod();
}
}
class Program {
static void Main(string[] args) {
Parent parent = new Parent();
Child child = new Child();
parent.SomeMethod(); // Output: Parent class method
child.SomeMethod(); // Output: Child class method
// Parent class method
}
}
When you run this code, the output would be:
Parent class method
Child class method
Parent class method
In this example:
-
The 'Parent' class defines a method named 'SomeMethod'.
- The 'Child' class inherits from 'Parent' and overrides the 'SomeMethod' method. Inside the overridden method, it calls the parent class method using 'base.SomeMethod()'.
- In the 'Main' method, we create instances of both the 'Parent' and 'Child' classes and call the 'SomeMethod' method on each instance.
When you call the overridden method of the 'Child' class, it first executes its own implementation ('"Child class method"'), and then using 'base.SomeMethod()', it calls the implementation of the 'SomeMethod' method from the Parent class ('"Parent class method"'). This allows you to leverage the behavior of the parent class method while extending or altering it in the child class's implementation.