Click here to Skip to main content
15,886,597 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
Hi, I was wondering what is the practical use of using a parent class reference variable to point to child class object instance in polymorphism? Can anybody elaborate on it with some real world problems that this type of instantiation solves?
Posted
Comments
Govindaraj Rangaraj 30-Sep-13 10:32am    
Are you asking this?

Class A
{}

Class B :Class A
{}

Main()
{
Class A = new Class B(); //why?

}

Consider following scenario...

I want to develop the new IDE.
I will provide support for various databases like mySql, oracle etc.

Now, I will develop one interface
C#
Interface MyInterface
{
  public int Insert();
  public List<object> Select(); 
}


I will give this Interface to DB providers for uniform implementation.

DB providers wouldn't allow me to see their implementation of those methods.

So to access those Methods what I need is to create the MyInterface's Reference and I will assign the object reference of the classes of DB provider.
This way I can access the methods of DB providers without seeing their internal implementation of code.

MySql DBProvider...
C#
class MySqlDBProvider : : MyInterface
{
    public override int Insert()
    {
       //here their Insert logic goes
    }
    public override List<Object> Select()
    {
       //here their Select logic goes
    }
}

Oracle DBProvider...
C#
class OracleDBProvider : MyInterface
{
    public override int Insert()
    {
       //here their Insert logic goes
    }
    public override List<Object> Select()
    {
       //here their Select logic goes
    }
}


Now what I need is...
C#
using MyInterfaceNamespace;
using MySqlDBProviderNamespace;
public class MyClass
{
   //here i will create reference of MyInterface
   //and assign Object of Your DB Provider Class.
   MyInterface MyIObj = new MySqlDBProvider();
   MyIObj.Insert();
   MyIObj.Select();

   //I can do the same for Oracle
}


Hope You Understand the importance of this feature in this kind of scenario.

Hope This Help
-----------------
Pratik Bhuva
 
Share this answer
 
v7
Comments
Abhinav Gauniyal 6-Oct-13 6:20am    
5ed :)
Thomas ktg 1-Nov-13 4:42am    
5ed
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900