-3

I have seen many examples on the concepts of inheritance, abstraction and polymorphism where an object of a base class is being initialized by a child class like below:

BaseClass obj1 = new ChildClass();

Most of the examples only used unreal and simple examples, but I always wanted to know the real life examples on what scenarios these can be used.

Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
  • 2
    There are thousands, if not millions, of such examples. Can you be a bit more specific about what is confusing you? By the way, thats not "initializing a base class object", you are just assigning a derived class instance to a base class reference (upcasting). – BradleyDotNET Jan 26 '15 at 23:18
  • Please don't ask such broad questions which are even not a real programming issue. See here: http://stackoverflow.com/help/how-to-ask – Quality Catalyst Jan 26 '15 at 23:37
  • I should have put this initially, why do I have to use Parent class object and assign it an instance of child class. – rocket.net Jan 27 '15 at 00:06

2 Answers2

0

Take Vehicle and Car as an example, where Vehicle is the superclass and Car is the subclass

Then you can write the code as

Vehicle vehicle = new Car();
Low Flying Pelican
  • 5,974
  • 1
  • 32
  • 43
0
class Program
{
    static void Main(string[] args)
    {
        var product = new Product();
        var status = product.Process();
    }
}

public class Product : Provider
{
    string provId = "ABC101";

    public bool Process()
    {
        var prodProv = new Provider(provId);
        this.QueryProvider();
        return true;
    }
}

public class Provider
{
    private string _providerId;

    public Provider(string provId)
    {
        _providerId = provId;
    }

    public void QueryProvider()
    {
        // Execute Provider logic here
    }
}
Raj Chaurasia
  • 1,976
  • 1
  • 11
  • 10