Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would one create a Base Class object with reference to the Derived Class

Tags:

c#

inheritance

I was practicing 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 a 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();
    }
}
like image 358
user3083590 Avatar asked Jul 05 '15 06:07

user3083590


2 Answers

I recommend you read about inheritance and Polymorphism in more detail. (here and here)

In this answer I try to keep concepts simple enough.

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

But in order to explain your question a bit lets take a look at simple and classic example of object oriented program that needs to use polymorphism.

Assume you are writing a program that needs to store some shapes and display them on screen. To achieve this you need to store all shapes in an array for example. right?

Suppose our classes are something like these:

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!");            
    }
}

And your array can be object array. like this:

object[] shapes = new object[10];

In your application you need to write a method to display shapes.

One solution can be iterating over all shapes and call right method of exact type of shape. like this:

public static void DisplayShapes_BAD(){

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

But what happens when another type of Shape appears in application? Basically you need to modify DisplayShapes_BAD() method to support new type of Shape (add new if statement to body of method)

This way you break Open/Closed principle of object oriented programming. and your code is not much maintainable.

Better way to store shapes to avoid this bad method is to use array of BaseShape. like this:

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

Here is how to add item to this list of shapes:

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

Now take a look at good implementation of DisplayShapes method.

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

In above method we call Display method on item with type of BaseShape. But how C# knows to call right method (for example circle display or rectangle display). This mechanism is Polymorphism.

Complete Code shared as Gist.

like image 94
farid bekran Avatar answered Sep 19 '22 07:09

farid bekran


As per my understanding in java,You are trying to call object of DerivedClass by using BaseClass reference varibale baseobj and this coding scenario is totally valid because it is providing the facility of runtime polymorphism.

Before runtime polymorphism lets understand the Upcasting. When reference variable of parent class is used to refer the object of child class then it is called as Upcasting

 class A{}

 class B extends A{}

 A obj= new B // Upcasting.

Runtime Polymorphism is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

Since you are not overriding show method in derived class,You are not doing runtime polymorphism but simply upcasting and upcasting is useful when we want to resolve the calling to overridden method at runntime.

like image 28
Abin Lakhanpal Avatar answered Sep 22 '22 07:09

Abin Lakhanpal