Can you access a hidden method of base class in the derived class which is declared in the base class?
Yes, you can access a hidden method of the base class in the derived class. When a method is hidden in the derived class, it means that the derived class has introduced a new method with the same name, effectively hiding the method from the base class.
However, you can still access the hidden method from the base class using eihter of the two ways:
-
By using 'base' keyword in the derived class.
- Make an object of the derived class, cast it into base class. This will call the the method of the base class.
Here's an example to illustrate this:
using System;
class Parent {
public void PrintMessage() {
Console.WriteLine("This is the Parent class.");
}
}
class Child : Parent {
public new void PrintMessage() {
Console.WriteLine("This is the Child class.");
}
public void AccessBasePrintMessage() {
base.PrintMessage(); // Accessing the hidden method from the base class
}
}
class Program {
static void Main(string[] args) {
Child child = new Child();
child.PrintMessage(); // Output: This is the Child class.
//1st - method
child.AccessBasePrintMessage(); // Output: This is the Parent class.
//2nd - method
Child child2 = new Child();
((Parent)child2).PrintMessage(); // Output: This is the Parent class.
}
}
Output:
This is the Child class.
This is the Parent class.
This is the Parent class.
In this example, the 'Child' class hides the 'PrintMessage' method from the 'Parent' class. However, using the 'AccessBasePrintMessage' method in the 'Child' class and the 'base' keyword, you can still access and call the hidden method from the base class ('Parent').
And in 2nd method you can cast the 'Child' class object into 'Parent' class and call the 'PrintMessage' method of the 'Parent' class.