Thinking in Java-polymorphic

Source: Internet
Author: User

In a Java object, an object can be used either as his own type or as his base type, calling this accumulation of reference an upward transformation

Package com.paragraph.one;public enum Note{middle_c,c_sharp,b_flat;}

Package Com.paragraph.one;public class Instrument {public instrument () {//TODO auto-generated constructor STUBSYSTEM.OUT.PRINTLN ("instrument");} public void Play (Note N) {System.out.println ("Instrument.play ()");}}

Package Com.paragraph.one;public class Wind extends Instrument{public wind () {//TODO auto-generated constructor Stubsyst Em.out.println ("Wind"); public void Play (Note N) {System.out.println ("Wind.play" +n);}}

Package Com.paragraph.one;public class Music {public static void tune (instrument i) {System.out.println (i); I.play ( Note.middle_c);} public static void Main (string[] args) {Wind flutewind = new Wind (); System.out.println (flutewind); tune (Flutewind);}}

The output is:

Instrument
Wind
[Email protected]
[Email protected]
Wind.playmiddle_c

Note that the method of wind is called above, not the base class.

Associating a method call with the same method body is called binding, and binding before the program executes is called early binding, and the generic C language, such as the process-oriented language, supports only early binding, which provides a late binding for the procedural language.

In addition to the static method and the final method in Java, the other methods are late-bound, so the preceding is the output wind method, but if you add the static method, it will call the play method in instrument.

Thinking in Java-polymorphic

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.