The difference between virtual, override, new and sealed override

前端 未结 4 672
情歌与酒
情歌与酒 2020-11-29 16:30

I\'m pretty confused between some concepts of OOP: virtual, override, new and sealed override. Can anyone explain the dif

4条回答
  •  北海茫月
    2020-11-29 17:06

     public class Base 
     {
       public virtual void SomeMethod()
       {
         Console.WriteLine("B");
       }
      }
    
    public class Derived : Base
    {
       //Same method is written 3 times with different keywords to explain different behaviors. 
    
    
       //This one is Simple method
      public void SomeMethod()
      {
         Console.WriteLine("D");
      }
    
      //This method has 'new' keyword
      public new void SomeMethod()
      {
         Console.WriteLine("D");
      }
    
      //This method has 'override' keyword
      public override void SomeMethod()
      {
         Console.WriteLine("D");
      }
    }
    

    Now First thing First

     Base b=new Base();
     Derived d=new Derived();
     b.SomeMethod(); //will always write B
     d.SomeMethod(); //will always write D
    

    Now the keywords are all about Polymorphism

     Base b = new Derived();
    
    1. Using virtual in base class and override in Derived will give D(Polymorphism).
    2. Using override without virtual in Base will give error.
    3. Similarly writing a method (no override) with virtual will write 'B' with warning (because no polymorphism is done).
    4. To hide such warning as in above point write new before that simple method in Derived.
    5. new keyword is another story, it simply hides the warning that tells that the property with same name is there in base class.
    6. virtual or new both are same except new modifier

    7. new and override cannot be used before same method or property.

    8. sealed before any class or method lock it to be used in Derived class and it gives a compile time error.

提交回复
热议问题