What is the real significance(use) of polymorphism

前端 未结 10 2339
别跟我提以往
别跟我提以往 2020-12-01 01:44

I am new to OOP. Though I understand what polymorphism is, but I can\'t get the real use of it. I can have functions with different name. Why should I try to implement polym

10条回答
  •  爱一瞬间的悲伤
    2020-12-01 02:05

    Advantage of polymorphism is client code doesn't need to care about the actual implementation of a method. Take look at the following example. Here CarBuilder doesn't know anything about ProduceCar().Once it is given a list of cars (CarsToProduceList) it will produce all the necessary cars accordingly.

    class CarBase
    {
        public virtual void ProduceCar()
        {
            Console.WriteLine("don't know how to produce");
        }
    }
    
    class CarToyota : CarBase
    {
        public override void ProduceCar()
        {
            Console.WriteLine("Producing Toyota Car ");
        }
    }
    
    class CarBmw : CarBase
    {
        public override void ProduceCar()
        {
            Console.WriteLine("Producing Bmw Car");
        }
    }
    
    class CarUnknown : CarBase { }
    
    class CarBuilder
    {
        public List CarsToProduceList { get; set; }
    
        public void ProduceCars()
        {
            if (null != CarsToProduceList)
            {
                foreach (CarBase car in CarsToProduceList)
                {
                    car.ProduceCar();// doesn't know how to produce
                }
            }
    
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            CarBuilder carbuilder = new CarBuilder();
            carbuilder.CarsToProduceList = new List() { new CarBmw(), new CarToyota(), new CarUnknown() };            
            carbuilder.ProduceCars();
        }
    }
    

提交回复
热议问题