Java Fundamentals Hardening 102: The understanding of polymorphism

Source: Internet
Author: User

1. In addition to the static method and the final method in Java (theprivate method is essentially the final method , because it cannot be accessed by a quilt), all other methods are dynamically bound. This means that normally we don't have to decide whether we should bind dynamically-it happens automatically.

The final method causes the compiler to generate more efficient code, which is why declaring the final method can improve performance to some extent (the effect is not obvious ).

2. The static method is not polymorphic , as shown in the following example code:

1 classStaticsuper {2      Public StaticString Staticget () {3         return"Base Staticget ()";4     }5      PublicString Dynamicget () {6         return"Base Dynamicget ()";7     }8 }9 classStaticsubextendsStaticsuper {Ten      Public StaticString Staticget () { One         return"Derived Staticget ()"; A     } -      PublicString Dynamicget () { -         return"Derived Dynamicget ()"; the     } - } -  Public classStaticpolymorphism { -      Public Static voidMain (string[] args) { +staticsuper sup =Newstaticsub (); - System.out.println (Sup.staticget ()); + System.out.println (Sup.dynamicget ()); A     } at}

Output:

Base Staticget ()

Derived Dynamicget ()

2. constructors are not polymorphic:

The constructor is actually a static method , except that the static declaration is implicit . Therefore, the constructor cannot be override.

Calling a function that has polymorphic behavior inside a parent class constructor will result in unpredictable results, because the subclass object is not initialized at this time, and calling the subclass method will not get the result we want.

The sample code is as follows:

1 classGlyph {2     voidDraw () {3System.out.println ("Glyph.draw ()");4     }5 Glyph () {6System.out.println ("Glyph () before Draw ()");7 Draw ();8System.out.println ("Glyph () after draw ()");9     }Ten } One classRoundglyphextendsGlyph { A     Private intRADIUS = 1; -Roundglyph (intr) { -Radius =R; theSystem.out.println ("Roundglyph.roundglyph (). Radius = "+radius); -     } -     voidDraw () { -System.out.println ("Roundglyph.draw (). Radius = "+radius); +     } - } +  Public classpolyconstructors { A      Public Static voidMain (string[] args) { at         NewRoundglyph (5); -     } -}

Output:

Glyph () before draw ()

Roundglyph.draw (). Radius = 0

Glyph () after draw ()

Roundglyph.roundglyph (). RADIUS = 5

Why is this output? This requires a clear understanding of the order in which constructors are called in Java?

(1) initialize the storage space allocated to the object into binary 0 before anything else occurs;

(2) call the base class constructor. Recursively from the root, since polymorphism calls the draw () method after the subclass overrides (to be called before calling the Roundglyph constructor), we will find that the radius value is 0 at this point because of step 1.

(3) The initialization method of invoking members in the Order of Declaration;

(4) The constructor of the subclass is called last.

3. Non-private methods can overwrite

Only non-private methods can be overwritten, but you also need to pay close attention to the behavior of the private method, while the compiler does not error, but it does not follow what we expect, that is, overriding the private method is a new method for a subclass rather than an overloaded method. Therefore, in a subclass, the new method name is best not to take the same name as the private method of the base class (though it doesn't matter, but is easy to misunderstand, to be able to override the private method of the base class).

The access operations for Domains in the Java class are parsed by the compiler and are therefore not polymorphic. Attributes with the same name as the parent and child classes will be allocated different storage spaces, as follows:

1 //Direct field access is determined at compile time.2 classSuper {3      Public intfield = 0;4      Public intGetField () {5         returnfield;6     }7 }8 classSubextendsSuper {9      Public intfield = 1;Ten      Public intGetField () { One         returnfield; A     } -      Public intGetsuperfield () { -         return Super. field; the     } - } -  Public classfieldaccess { -      Public Static voidMain (string[] args) { +Super sup =NewSub (); -System.out.println ("sup.filed =" + Sup.field + +", Sup.getfield () =" +Sup.getfield ()); ASub Sub =NewSub (); atSystem.out.println ("sub.filed =" + Sub.field + -", Sub.getfield () =" + Sub.getfield () + -", Sub.getsuperfield () =" +Sub.getsuperfield ()); -     } -}

Output:

sup.filed = 0, Sup.getfield () = 1

sub.filed = 1, Sub.getfield () = 1, Sub.getsuperfield () = 0

Analysis:

The sub subclass actually contains two fields called field, whereas the default domain generated when referencing field in sub is not a super version of the Field field, so in order to get Super.field, you must explicitly indicate Super.field.

Java Fundamentals Hardening 102: The understanding of 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.