Compile time polymorphism vs. run time polymorphism

后端 未结 9 2252
栀梦
栀梦 2020-12-23 00:15

Why is overloading called compile time polymorphism and Overriding run time polymorphism in C#?

9条回答
  •  甜味超标
    2020-12-23 00:19

    compile time polymorphism

    Suppose lets say you have 2 methods as follows; since the method shares same name but have different parameters; it is called as "overloaded" method. Eat(string food); Eat(string food, string SpoonOrFork);

    and you are using like this in your dinner class

    public class Man
    {
     public bool Eat (string food)
     {
      //implementation
     }
    
     public bool Eat (string food, string SpoonOrFork)
     {
      //implementation
     }
    
    }
    public class dinner
    {
      public bool Start()
      {
       string food = "course1";
       Man.Eat ( food);
      }
    }
    

    Now when you compile this program the compiler knows exactly which version of Eat method to call during compile time itself (because of the difference in parameters).

    That's why it is called as compile time polymorphism.

    Run time polymorphism

    public class chimp
        {
            public virtual void walk()
            {
                Console.WriteLine("I am walking using 4 legs");
            }
    
        }
    
        public class neanderthals : chimp
        {
            public override void walk()
            {
                Console.WriteLine("I am walking using 2 legs");
            }
    
        }
    
    
    
        class Program
        {
            static void Main(string[] args)
            {
                chimp x = new neanderthals();
                x.walk();
                Console.ReadLine(); // this will give an output of "I am walking using 2 legs"
            }
        }
    

    In the above code x is of type chimp. Even though the compiler thinks it is going to call the walk method in chimp; but that is not what actually happens. Since it depends on CLR (run time) this kind of polymorphism is called "run-time" polymorphism.

提交回复
热议问题