Difference between new and override

后端 未结 14 1635
再見小時候
再見小時候 2020-11-22 05:36

Wondering what the difference is between the following:

Case 1: Base Class

public void DoIt();

Case 1: Inherited class

<         


        
14条回答
  •  迷失自我
    2020-11-22 05:46

    The difference between the two cases is that in case 1, the base DoIt method does not get overridden, just hidden. What this means is that depending on the type of the variable depends on which method will get called. For example:

    BaseClass instance1 = new SubClass();
    instance1.DoIt(); // Calls base class DoIt method
    
    SubClass instance2 = new SubClass();
    instance2.DoIt(); // Calls sub class DoIt method
    

    This can be really confusing and results in non expected behaviour and should be avoided if possible. So the preferred way would be case 2.

提交回复
热议问题