Inheritance (Base Class, Sub-Class) - What is the output?

public class A
{
    public A()
    {
        Console.WriteLine("Class A");
    }
}

public class B : A
{
    public B()
    {
        Console.WriteLine("Class B");
    }
}

public class C : B
{
    public C()
    {
        Console.WriteLine("Class C");            
    }
}

C objC = new C();

Option 1: Class A
Option 2: Class B
Option 3: Class C
Option 4: Class C Class B Class A
Option 5: Class A Class B Class C

Answer: Option 5: Class A Class B Class C


Explanation: Constructors that are declared within a base class, are not inherited by sub-classes. As with any other class, a sub-class with no constructors defined is provided with a default constructor, that provides no explicit functionality.
The constructors from the base class are not made available when creating new sub-class object instances. When a sub-class is instantiated, the standard behavior is for the default constructor of the base class to be called automatically.
In this way the base constructor can initialize the base class before the sub-class' constructor is executed.

No comments:

Post a Comment