The difference between virtual, override, new and sealed override

前端 未结 4 660
情歌与酒
情歌与酒 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.
    0 讨论(0)
  • 2020-11-29 17:08

    Any method can be overridable (=virtual) or not. The decision is made by the one who defines the method:

    class Person
    {
        // this one is not overridable (not virtual)
        public String GetPersonType()
        {
            return "person";
        }
    
        // this one is overridable (virtual)
        public virtual String GetName()
        {
            return "generic name";
        }
    }
    

    Now you can override those methods that are overridable:

    class Friend : Person
    {
        public Friend() : this("generic name") { }
    
        public Friend(String name)
        {
            this._name = name;
        }
    
        // override Person.GetName:
        public override String GetName()
        {
            return _name;
        }
    }
    

    But you can't override the GetPersonType method because it's not virtual.

    Let's create two instances of those classes:

    Person person = new Person();
    Friend friend = new Friend("Onotole");
    

    When non-virtual method GetPersonType is called by Fiend instance it's actually Person.GetPersonType that is called:

    Console.WriteLine(friend.GetPersonType()); // "person"
    

    When virtual method GetName is called by Friend instance it's Friend.GetName that is called:

    Console.WriteLine(friend.GetName()); // "Onotole"
    

    When virtual method GetName is called by Person instance it's Person.GetName that is called:

    Console.WriteLine(person.GetName()); // "generic name"
    

    When non-virtual method is called the method body is not looked up - compiler already knows the actual method that needs to be called. Whereas with virtual methods compiler can't be sure which one to call, and it is looked up at runtime in the class hierarchy from down to up starting at the type of instance that the method is called on: for friend.GetName it looks starting at Friend class and finds it right away, for person.GetName class it starts at Person and finds it there.

    Sometimes you make a subclass, override a virtual method and you don't want any more overrides down in the hierarchy - you use sealed override for that (saying you are the last one who overrides the method):

    class Mike : Friend
    {
        public sealed override String GetName()
        {
            return "Mike";
        }
    }
    

    But sometimes your friend Mike decides to change his gender and thus his name to Alice :) You could either change original code or instead subclass Mike:

    class Alice : Mike
    {
        public new String GetName()
        {
            return "Alice";
        }
    }
    

    Here you create a completely different method with the same name (now you have two). Which method and when is called? It depends on how you call it:

    Alice alice = new Alice();
    Console.WriteLine(alice.GetName());             // the new method is called, printing "Alice"
    Console.WriteLine(((Mike)alice).GetName());     // the method hidden by new is called, printing "Mike"
    

    When you call it from Alice's perspective you call Alice.GetName, when from Mike's - you call Mike.GetName. No runtime lookup is made here - as both methods are non-virtual.

    You can always create new methods - whether the methods you are hiding are virtual or not.

    This applies to properties and events too - they are represented as methods underneath.

    0 讨论(0)
  • 2020-11-29 17:11

    The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it: Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.

    This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class. For instance:

    public class Base
    {
      public virtual void SomeMethod()
      {
      }
    }
    
    public class Derived : Base
    {
      public override void SomeMethod()
      {
      }
    }
    
    ...
    
    Base d = new Derived();
    d.SomeMethod();
    

    will end up calling Derived.SomeMethod if that overrides Base.SomeMethod.

    Now, if you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it. In that case, code like this:

    public class Base
    {
      public virtual void SomeOtherMethod()
      {
      }
    }
    
    public class Derived : Base
    {
      public new void SomeOtherMethod()
      {
      }
    }
    
    ...
    
    
    Base b = new Derived();
    Derived d = new Derived();
    b.SomeOtherMethod();
    d.SomeOtherMethod();
    

    Will first call Base.SomeOtherMethod , then Derived.SomeOtherMethod . They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.

    If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).

    An overriding property declaration may include the sealed modifier. Use of this modifier prevents a derived class from further overriding the property. The accessors of a sealed property are also sealed.

    0 讨论(0)
  • 2020-11-29 17:12

    By default a method cannot be overridden in a derived class unless it is declared virtual, or abstract. virtual means check for newer implementations before calling and abstract means the same, but it is guaranteed to be overridden in all derived classes. Also, no implementation is needed in the base class because it is going to be re-defined elsewhere.

    The exception to the above is the new modifier. A method not declared virtual or abstract can be re-defined with the new modifier in a derived class. When the method is called in the base class the base method executed, and when called in the derived class, the new method is executed. All the new keywords allows you to do is to have two methods with the same name in a class hierarchy.

    Finally a sealed modifier breaks the chain of virtual methods and makes them not overridable again. This is not used often, but the option is there. It makes more sense with a chain of 3 classes each deriving from the previous one

    A -> B -> C
    

    if A has an virtual or abstract method, that is overridden in B, then it can also prevent C from changing it again by declaring it sealed in B.

    sealed is also used in classes, and that is where you will commonly encounter this keyword.

    I hope this helps.

    0 讨论(0)
提交回复
热议问题