c method overrides and hides learning examples

  • 2020-06-12 10:17:36
  • OfStack

Recently working on c#, the concepts of method overrides and concealment were very vague, and now they are summarized as follows:

1: Method override: A method in a base class is identified by the virtual keyword and then overridden in an inherited class (override) so that the method in the base class has been overridden and is no longer functional. When a reference to an object of a base class is made directly to an object of an inherited class (polymorphism), calling that method is the method of the invoked inherited class.

Method 2: hidden: whether in the base class method with the virtual keywords, can use new keyword in a derived class (if not new, won't produce errors, but will generate a compiler warning) will be hidden in the base class method, the so-called hidden is hidden, unlike rewrite, rewrite is original (base class) is no longer exist, and hidden is still exist. So when you make a reference to an object of a base class directly to an object of an inherited class (polymorphism), calling that method is the method of the calling base class.

The code is as follows:


public class BaseClass
    {
        public void functionA()
        {
            Console.WriteLine("BaseFunctionA https://www.ofstack.com/sosoft/");
        }
        public virtual void functionB()
        {
            Console.WriteLine("BaseFunctionB https://www.ofstack.com/sosoft/");
        }
    }
   public class DerivedClass:BaseClass
    {
        public new void functionA()
        {
            Console.WriteLine("DerivedFunctionA https://www.ofstack.com/sosoft/");
        }
        public override void functionB()
        {
            Console.WriteLine("DerivedFunctionB https://www.ofstack.com/sosoft/");
        }
    }

When polymorphism is used to execute the following code:


BaseClass baseFunction=new DerivedClass();
baseFunction.functionA();
baseFunction.functionB();

The results are as follows:


BaseFunctionA https://www.ofstack.com/sosoft/
DerivedFunctionB https://www.ofstack.com/sosoft/


Related articles: