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 DerivedCla
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 Shapes = new List();
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.