Why create an object of a base class with reference to a derived class

I practiced inheritance using a test program in C #, and I found out that the following statement does not throw an error:

BaseClass baseObj = new DerivedClass();

Why is this statement allowed and is there a situation where this statement would be useful to the programmer?

Here is my test program:

class BaseClass
{
    public void show()
    {
        Console.WriteLine("Base Class!");

    }
}

class DerivedClass : BaseClass
{
    public void Display()
    {
        Console.WriteLine("Derived Class!");            
    }
}

class Result
{
    public static void Main()
    {            
        BaseClass baseObj = new DerivedClass();
        baseObj.show();
    }
}
+4
source share
3 answers

I recommend that you read more about inheritance and polymorphism. ( here and here )

In this answer, I try to keep the concepts simple enough.

Why is this statement allowed and is there a situation where this statement would be useful for the programmer?

, , - , .

, , . , . ?

, :

class BaseShape
{
    public virtual void Display()
    {
        Console.WriteLine("Displaying Base Class!");

    }
}

class Circle : BaseShape
{
    public override void Display()
    {
        Console.WriteLine("Displaying Circle Class!");            
    }
}

class Rectangle : BaseShape
{
    public override void Display()
    {
        Console.WriteLine("Displaying Rectangle Class!");            
    }
}

object. :

object[] shapes = new object[10];

.

. :

public static void DisplayShapes_BAD(){

    foreach(var item in Shapes)
    {
        if(typeof(Circle) == item.GetType())
        {
            ((Circle)item).Display();
        }
        if(typeof(Rectangle) == item.GetType())
        {
            ((Circle)item).Display();
        }
    }
}

, Shape? DisplayShapes_BAD() Shape ( if )

/ - . .

- BaseShape. :

public static List<BaseShape> Shapes = new List<BaseShape>();

:

Shapes.Add(new Circle());
Shapes.Add(new Rectangle());

DisplayShapes.

public static void DisplayShapes_GOOD()
{
    foreach(var item in Shapes)
    {
        item.Display();
    }
}

Display BaseShape. # , (, ). .

, Gist.

+10

, , , , ( ). : .net , object baseObj = new DerivedClass().

, , - , (). , , . BaseClass, , , BaseClass. BaseClass baseObj = new DerivedClass(), , BaseClass, DerivedClass , BaseClass.

, BaseClass (BaseClasses ), BaseClass , , , .

, , , , BaseClass, . :

BaseClass baseObj = SomeCriterium ? (BaseClass)new DerivedClass() : new AlternateDerivedClass(); 

, - , BaseClass, , , BaseClass () , DerivedClass.

, ( , , , ):

IEnumerable<T> values = new List<T>();
if(needfilter)
    values = values.Where(el => filtercriterium);

, . , . , .

+2

java, DerivedClass baseClass varibale baseobj, , .

. , Upcasting

 class A{}

 class B extends A{}

 A obj= new B // Upcasting.

- , , .

show , , , .

+1

All Articles