Is polymorphism another term for overloading?

前端 未结 4 1526
感动是毒
感动是毒 2020-12-13 07:23

Is polymorphism another term for overloading?

4条回答
  •  伪装坚强ぢ
    2020-12-13 07:40

    No, it is not.

    Overloading refers to creating a method or an operator with the same name, but different parameters and - depending on the language - different return types.

    Overriding refers to reimplementing a method with the same signature in a derived class and enables polymorphism - the decision what implementation of an overwritten method to call is made at runtime depending on the actual type of the object.

    class BaseClass
    {
         public void DoStuff(Int32 value) { } // Overloading
    
         public void DoStuff(String value) { } // Overloading
    
         public virtual void DoOtherStuff(String value) { }
    }
    
    class DerivedClass : BaseClass
    {
        public override void DoOtherStuff(String value) { } // Overriding
    }
    

    Usage example

    BaseClass instance = null;
    
    if (condition)
    {
        instance = new BaseClass();
    }
    else
    {
        instance = new DerivedClass();
    }
    
    // Using overloads
    instance.DoStuff(4);
    instance.DoStuff("four");
    
    // Polymorphism - it depends on the actual type of the object
    // referenced by the variable 'instance' if BaseClass.DoOtherStuff()
    // or DerivedClass.DoOtherStuff() will be called at runtime.
    instance.DoOtherStuff("other stuff");
    

提交回复
热议问题