Syntax differences between C # and Java polymorphism
2016-11-29
Java code:
Public Static voidMain (string[] args) {Mother Mother=Newmother (); Mother.showname (); Mother Human=NewSon (); Human.showname (); Son Sona=NewSon (); Sona.showname ();} Public classMother { Public voidShowName () {System.out.println (Mom); }} Public classSonextendsMother { Public voidShowName () {System.out.println (Son); } }
Results:
Mom Son son
C # code:
classProgram { Public Static voidMain () {Mother Mother=Newmother (); Mother. ShowName (); Mother Human=NewSon (); Human. ShowName (); Son Sona=NewSon (); Sona. ShowName (); Console.read (); } } Public classMother { Public Virtual voidShowName () {Console.WriteLine ("mom"); } } Public classSon:mother { Public Override voidShowName () {Console.WriteLine ("son"); } }
Results:
Mom Son son
but if the override is gone, a line of warnings will appear, but the compiler will not error:
Warning 1 "ConsoleApplication1.Son.ShowName ()" Hides the inherited member "ConsoleApplication1.Mother.ShowName ()". If it is intentionally hidden, use the keyword new
The result is:
Mom Mom Son
Conclusion:
This proves that C # does not support polymorphism by default, and subclasses have a new keyword by default. C # to implement more than one need to add virtual and override before a method
In addition, polymorphism refers to the method, see only Polymorphic method, no polymorphic instance field
Syntax differences between C # and Java polymorphism