The new Keyword is used to hide the base class implementation of the same. But I am not sure why the following code produces the output as Baseclass
class Baseclass
{
public void fun()
{
Console.Write("Base class" + " ");
}
}
class Derived1: Baseclass
{
new void fun()
{
Console.Write("Derived1 class" + " ");
}
}
class Derived2: Derived1
{
new void fun()
{
Console.Write("Derived2 class" + " ");
}
}
class Program
{
public static void Main(string[ ] args)
{
Derived2 d = new Derived2();
d.fun();
}
}
We are hiding the implementation of fun in derived2 but still Base class is called why so? Am I missing something?
Derived2.fun
is private (it is the default access modifier of the members of the type). It is not visible outside the class. Only visible fun
method outside the class is Baseclass.fun
and thus it is invoked.
You need to make your Derived2.fun
visible outside the class to get the expected output. You can do it by either making it public/internal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With