In object-oriented languages, inheritance and polymorphism are important two characteristics. At present, both C # and Java are single-inheritance multi-interface languages , and can effectively use object-oriented features for programming. Where inheritance is a process that materializes a class, the higher the inheritance depth, the more specific the class. Polymorphism is the interface that implements the same function with different materialization methods, so that the parent class has the characteristics of subclasses. At the same time polymorphism can be used to implement code reuse.
1. Virtual method
The virtual method defines a virtual function in a base class that can be inherited by a quilt class and overridden in a subclass into a new function with a subclass attribute. Like what:
public virtual int sum () {}//... In the base class
public override int sum () {}//... In the child class
Note that the override keyword in C #, overriding a function in a subclass, when the base class changes this function, the subclass does not change and plays the role of protection.
2. New modifier
In contrast with override, new can show hidden member functions inherited from the base class. Although all use subclasses ' own functions, new hides and truncates the function of the base class, and override expands the function of the base class function. Let's look at an example:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 7 namespaceConsoleApplication18 {9 class ProgramTen { One Static voidMain (string[] args) A { -A Obja =NewD (); -A OBJB =NewB (); theC OBJC =NewD (); -A OBJD =NewA (); - Obja.movie (); - Objb.movie (); + Objc.movie (); - Objd.movie (); + A } at classA { - Public Virtual voidMovie () { -Console.WriteLine ("Mikimouse"); - } - } - classb:a { in Public Override voidMovie () { -Console.WriteLine ("Disneymovie"); to } + } - the classc:b { * Public New Virtual voidMovie () { $Console.WriteLine ("Snow White");Panax Notoginseng } - } the classD:c { + Public Override voidMovie () { AConsole.WriteLine ("Seven dwarfs"); the } + } - $ } $}
The output is:
In short, new virtual is the equivalent of a breakpoint that truncates the inheritance stream.
Some things about inheritance and polymorphism in C # ...