A tour of reading original TIJ English books -- Chapter Eight: Polymorphism, tijpolymorphism

Source: Internet
Author: User

A tour of reading original TIJ English books -- Chapter Eight: Polymorphism, tijpolymorphism

The twist

| _ Method-call binding

Connecting a method call to a method body is called binding. when binding is performed med before the program is run (by the compiler and linker, if there is one), it's called early binding. you might not hava heard the term before because it has never been an option with procedural ages. C compilers hava only one kind of method call, and that's early binding.

When a language implements late binding, there must be some mechanisms to determine the type of the object at run time and to call the appropriate method. that is, the compiler still doesn't know the object type, but the method-call mechanic finds out and callthe correct method body. the late-binding mechanic varies from language to language, but you can imagine the some sort of type information must be installed in the objects.

All method binding in Java uses late binding unless the method is static or final (private method are implicitly final ). this means that ordinarily you don't need to make any demo-about whether late binding will occur-it happens automatically.

| _ Pitfall: "overriding" private methods

Here's something you might innocently try to do:

public class PrivateOverride{private void f() {System.out.println("private f()");}public static void main(String[] args){PrivateOverride po = new Derived();po.f(); }}class Derived extends PrivateOverride{public void f() {System.out.println("public f()");}}/*Output:private f()*/

You might reasonably expect CT the output to be "public f ()", but a private method is automatically final, and is also hidden from the derived class. so Derived's f () in the case is a brand new method; it's not even overloaded, since the base-class version of f () isn' t visible in Derived. if you want to get the "public f ()", you can modify that code po. f () to (Derived) po ). f ().

The result of this is that only non-private methods may be overridden, but you shoshould watch out for the appearance of overriding private methods, which generates no compiler warnings, but doesn' t do what you might wrong CT. to be clear, you should use a different name from a private base-class method in your derived class.

| _ Pitfall: fields and static methods

Once you learn about polymorphism, you can begin to think that everything happens polymorphically. however, only ordinary method CILS can polymorphic. if you access a field directly, that access will be resolved at compile time.

Although this seems like it cocould be a confusing issue, in practice it always Ally never comes up. for one thing, you'll generally make all fields private and so you won't access them directly, but only as side effects of calling methods, In addition, you probably won't give the same name to base-class field and a derived-class field, because its confusing.

If a method is static, it doesn't behave polymorphically, static methods are associated with the class, and not the individual objects.

Constructors and polymorphism

| _ Order of constructor cballs

Even though constructors are not polymorphic (they're actually static methods, but the static declaration is implicit), it's important to understand the way constructors work in complex hierarchies and with polymorism.

A constructor for the base class is always called during the construction process for a derived class, chaining up the inheritance hierarchy so that a constructor for every base class is called.

The order of constructor cballs for a complex object is as follows:

1. the base-class constructor is called. this step is repeated recursively such that the root of the hierarchy is constructed first, followed by the next-derived class, etc ., until the most-derived class is reached.

2. Member initializers are called in the order of declaration.

3. The body of the derived-class constructor is called.

The order of the constructor cballs is important. when you inherit, you know all about the base class and can access any public and protected members of the base class. this means that you must be able to assume that all the members of the base class are valid when you're members of all parts of the object have been built. inside the constructor, however, you must be able to assume that all members that you use hava been built. the only way to guarantee this is for the base-class constructor to be called first. then when you're in the derived-class constructor, all the members you can access in the base class have been initialized. knowing that all members are valid inside the constructor is also the reason that, whenever possible, you shoshould initialize all member object (that is, objects placed in the class using composition) at their point of definition in the class. if you follow this practice, you will heap ensure that all base class members and members objects of the current object have been initialized.

| _ Inheritance and cleanup

When you override dispose () (the name I have chosen to use here; you may come up with something better) in an inherited class, it's important to remember to call the base-class version of dispose (), since otherwise the base-class cleanup will not happen.

| _ Behavior of polymorphic methods inside constructors

Conceptually, the constructor's job is to bring the object into existence (which is hardly an ordinary feat ). inside any constructor, the entire object might be only partially formed-you can only know that the base-class objects have been initialized. if the constructor is only one step in building an object of a class that's been derived from that constructor's class, the derived parts have not yet been initialized at the time that the current constructor is being called. A dynamic bound method call, however, reaches "outward" into the inheritance hierarchy. it calla method in a derived class. if you do this inside a constructor, you call a method that might manipulate members that haven't been initialized yet-a sure recipe for disaster.

You can see the problem in the following example:

class Glyph{void draw() {System.out.println("Glyph.draw()");}Glyph(){System.out.println("Glyph() before draw()");draw();System.out.println("Glyph() after draw()");}}class RoundGlyph extends Glyph{private int radius = 1;RoundGlyph(int r){radius = r;System.out.println("RoundGlyph.RoundGlyph(), radius = " + radius);}void draw(){System.out.println("RoundGlyph.draw(), radius = " + radius);}}public class PolyConstructors{public static void main(String[] args){new RoundGlyph(5);}}/* Output:Glyph() before draw()RoundGlyph.draw(), radius = 0Glyph() after draw()RoundGlyph.RoundGlyph(), radius = 5*/

The order of initialization described in the earlier section isn't quite complete, and that's the key to solving the mystery. The actual process of initialization is:

1. The storage allocated for the object is initialized to binary zero before anything else happens.

2. the base-class constructors are called as described previusly. at this point, the overridden draw () method is called (yes, before the RoundGlyph constructor is called), which discovers a radius value of zero, due to Step 1.

3. Member initializes are called in the order of declaration.

4. The body of the derived-class constructor is called.

For avoid this problem, a good guideline for constructors is, "Do as little as possible to set the object into a good state, and if you can possibly avoid it, don't call any other methods in this class. "The only safe methods to call inside a constructor are those that are final in the base class. (This also applies to private methods, which are automatically final .) these cannot be overridden and thus cannot produce this kind of surprise. you may not always be able to follow this guideline, but it's something to strive.

Covariant return types

Java SE5 adds covariant return types, which means that an overridden method in a derived class can return a type derived from the type returned by the base-class method.

Designing with inheritance

A general guideline is "Use inheritance to express differences in behavior, and fields to express variations in state ".

 

(END_XPJIANG)

Related Article

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.