suri
suri

Reputation: 37

Please correct me with OOP inheritance

I thought it will call the derived class function because class will give importance to its own function but it is calling base class function please correct me...

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 test
{
  static void Main(string[] args)
  {
    Derived2 d = new Derived2();
    d.fun(); 
  }
}

Upvotes: 0

Views: 35

Answers (1)

Sweeper
Sweeper

Reputation: 271040

The base class method is called because only the base class method is accessible.

Why aren't the other methods accessible? Let's look at the method in Derived2:

new void fun()
{
  Console.Write("Derived2 class" + " ");
}

What is its access modifier? None, so it defaults to private. This means that you can't access this method from test class!

To make it work, simply add a public modifer:

new public void fun()
{
  Console.Write("Derived2 class" + " ");
}

Upvotes: 1

Related Questions