Syntax differences between C # and Java polymorphism

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.