C# Programming - Inheritance - Discussion

Discussion Forum : Inheritance - General Questions (Q.No. 6)
6.
What will be the output of the C#.NET code snippet given below?
namespace IndiabixConsoleApplication
{ 
    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(); 
        } 
    } 
}
Base class
Derived1 class
Derived2 class
Base class Derived1 class
Base class Derived1 class Derived2 class
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
28 comments Page 3 of 3.

Arvind said:   1 decade ago
The answer should be Derived 2, the access specifier doesn't put any difference.

Sandeep Singh said:   1 decade ago
Functions of class Derived1 and Derived2 are inaccessible due to its protection level i.e private (default access specifier). So it will access the function of Base Class because its public.

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

Deriver2 Class will Execute.

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

Deriver1 Class will Execute..
(5)

VENDI said:   1 decade ago
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public new void Foo() { Console.WriteLine("B::Foo()"); } //make this function public.......else the base class function will be called
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "A::Foo()"
}

Lingaswamy said:   10 years ago
In new key work use before void fun() then it will be hide of that fun() method.

If you want to invoke Derived2 class void fun() method, add virtual void fun() in Base class and add override void fun() in Derived2.

Ishwar said:   9 years ago
Virtual Keyword are required in base class.

Mohammad Adil said:   9 years ago
Output: Derived2.

Here the new keyword only hides the compile time error which showing the hiding of base class method by derived class method.

So here the output is Derived2 because Derived1 hides base class method and Derived2 hides Derived1 class method because they have the same signature.
(1)

Harika said:   4 years ago
Sealed key word stops the inheritance execution.
(1)

Ankita Bhagat said:   2 years ago
Yes, the Answer is Base class.


Post your comments here:

Your comments will be displayed after verification.