Bingfoot
Bingfoot

Reputation: 21

About Inheritance

Why does this code produce the output "Base class" and not "Derived2 class"?

namespace TestConsoleApplication
{ 
    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(); 
        } 
    } 
}

Upvotes: 1

Views: 99

Answers (1)

Rob
Rob

Reputation: 27357

Because you didn't declare the method as public.

You've told it to hide the original definition, rather than override it - which it will do, but the default access modifier is private, not public.

For example, when calling the method from within Derived2:

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

    public void Test()
    {
        fun();
    }
}
class Program
{
    public static void Main(string[] args)
    {
        Derived2 d = new Derived2();
        d.Test(); //Prints 'Derived2 class'
    }
}

Setting it to public will indeed print Derived2 in your original example

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

Upvotes: 4

Related Questions