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 2 of 3.

Shubhra said:   1 decade ago
I did not understand the output.

The new keyword in function decelration? what would it do?

If new was not there then Derived2 should be answer?

If instead of Fun they were contructors then what?

Harsh said:   1 decade ago
Default access modifiers for member function of class is private.

Since no access modifiers is specified in derive class, it is private.

So it is accesible, so base class method will be called.

Mihi said:   1 decade ago
Since in derived classes for functions no access specifiers specified so those will not inherit. The final method that should inherit is Base class fun(). The output is "Base class"

Amit 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.

Shanal said:   1 decade ago
The 'new' keyword if use with derived class variable it hides the variable of same name in the base class and if same is the case with member func then the output should be derived2.

Vapandian said:   1 decade ago
This is simple. Because other func() are not having public, only base class having public func() ; so this is only executed. If you provide public to derived 2 it will execute.

Vidit Tyagi said:   1 decade ago
We need to use virtual keyword in base then we can hide the functionality of base class method with the help of new keyword :).

Vaibhav M Nalwad said:   1 decade ago
When you add a new keyword for a property, variable, Method it is said to be Shadowing so the output would be "".

Prashant said:   1 decade ago
Output should be "Derived2 class" because there is no base.fun() in program to calling the baseclass.

Vikas said:   1 decade ago
I m not understanding the output. Since there is new keyword,Output should be "Derived2 class".


Post your comments here:

Your comments will be displayed after verification.