Can a derived class reference contain base class object.

1)Can a derived class reference contain base class object.


using System;
public class Base
        {
        public Base()
        {
        Console.WriteLine("I am from the Base Class Constructor");

        }
        public void  Invert()
        {
        Console.WriteLine("I am an invert function and I belong to Base");
        }

        }

public class Derived:Base
        {
        public Derived()
        {
        Console.WriteLine("I am from the derived class constructor");
        }
        public new void Invert()
        {
        Console.WriteLine("I am purely from the derived class");
        }
        public void BaseInvert()
        {
        Console.WriteLine("I am  from the Derived class by I will implement the base class");
        base.Invert();
        }


        }

class Program
        {
        public static void Main()
        {
        Derived d =new Derived();
        d.BaseInvert();
        d.Invert();

        Base d_= new Derived();
        d_.Invert();


        Derived d2 =new Base();
        d2.Invert();
        Console.ReadLine();
        }
        }
         

No, that's not possible since assigning it to a derived class reference would be like saying "Base class is a fully capable substitute for derived class, it can do everything the derived class can do", which is not true since derived classes in general offer more functionality than their base class (at least, that's the idea behind inheritance)

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6