- Method substitution
- After the subclass inherits the parent class, you can hide the method in the parent class and re-implement it in the subclass
- Virtual functions and overrides
- The method of virtual modification is called the virtual method, and the override method is called rewriting.
- Only methods and properties can be virtual, fields cannot be virtual
- The difference between abstract and virtual methods
- 1. The abstract method must be in an abstract class, and the virtual method may not.
- 2. Abstract methods cannot be implemented in a parent class, and virtual methods can not.
- 3. Abstract methods must be implemented in non-abstract subclasses, and virtual methods can not
- Polymorphic--Uses the parent class type to invoke the method implemented in the subclass
1 usingSystem;2 3 namespaceVirtualmethoddemo4 {5 Public classSuper6 {7 Public Virtual stringName8 {9 GetTen { One return "Li"; A } - } - the Public voidA () - { -Console.WriteLine ("This method is defined in Super in a! "); - } + //virtual Method - + //the difference between abstract and virtual methods A //1. The abstract method must be in an abstract class, and the virtual method may not. at //2. Abstract methods cannot be implemented in a parent class, and virtual methods can not. - //3. Abstract methods must be implemented in non-abstract subclasses, and virtual methods can not - Public Virtual voidB () - { -Console.WriteLine ("This method is the B defined in Super! "); - } in } - to Public classSub:super + { - the Public Override stringName * { $ GetPanax Notoginseng { - return "Zhao"; the } + } A //method Substitution-Re-implementing the method defined in the parent class in the subclass the Public New voidA () + { -Console.WriteLine ("This method is defined in Sub in a! "); $ } $ - //virtual Method - //This method can not be written. the Public Override voidB () - {WuyiConsole.WriteLine ("This method is the B defined in Sub! "); the } - } Wu class Program - { About Static voidMain (string[] args) $ { - //referencing the parent class object using the parent class type -Super Super =NewSuper (); -Super. A ();//called a method defined in the parent class ASuper. B ();//called a method defined in the parent class + Console.WriteLine (Super. Name); the - //referencing child class objects using subclass Types $Sub Sub =NewSub (); theSub. A ();//called a method defined in a subclass theSub. B ();//called a method defined in a subclass the Console.WriteLine (Sub. Name); the - //referencing a subclass object using the parent class type inSuper C =NewSub (); theC.A ();//called a method defined in the parent class theC.B ();//called a method defined in a subclass About Console.WriteLine (c.name); the the //polymorphic--Uses the parent class type to invoke the method implemented in the subclass the } + } -}
"Learning notes" C # virtual method (virtual function)