Difference between new and override

后端 未结 14 1496
再見小時候
再見小時候 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 06:10

    The functional difference will not be show in these tests:

    BaseClass bc = new BaseClass();
    
    bc.DoIt();
    
    DerivedClass dc = new DerivedClass();
    
    dc.ShowIt();
    

    In this exmample, the Doit that is called is the one you expect to be called.

    In order to see the difference you have to do this:

    BaseClass obj = new DerivedClass();
    
    obj.DoIt();
    

    You will see if you run that test that in the case 1 (as you defined it), the DoIt() in BaseClass is called, in case 2 (as you defined it), the DoIt() in DerivedClass is called.

    0 讨论(0)
  • 2020-11-22 06:11

    At the first case it will call derived class DoIt() method because new keyword hides base class DoIt() method.

    At the second case it will call overriden DoIt()

      public class A
    {
        public virtual void DoIt()
        {
            Console.WriteLine("A::DoIt()");
        }
    }
    
    public class B : A
    {
        new public void DoIt()
        {
            Console.WriteLine("B::DoIt()");
        }
    }
    
    public class C : A
    {
        public override void DoIt()
        {
            Console.WriteLine("C::DoIt()");
        }
    }
    

    let create instance of these classes

       A instanceA = new A();
    
        B instanceB = new B();
        C instanceC = new C();
    
        instanceA.DoIt(); //A::DoIt()
        instanceB.DoIt(); //B::DoIt()
        instanceC.DoIt(); //B::DoIt()
    

    Everything is expected at above. Let set instanceB and instanceC to instanceA and call DoIt() method and check result.

        instanceA = instanceB;
        instanceA.DoIt(); //A::DoIt() calls DoIt method in class A
    
        instanceA = instanceC;
        instanceA.DoIt();//C::DoIt() calls DoIt method in class C because it was overriden in class C
    
    0 讨论(0)
提交回复
热议问题