Sunday, January 25, 2015

[Java]Polymorphism


The article is mainly the summary of book "Thinking in Java" from Page 277 to Page 310.

Polymorphism:

  1. Polymorphism allows us to forget the derived classes and write the code to talk only the base class, namely, allows us to work on the same interface even though we have many derived classes.
  2. If we declare a reference of base class and point it to derived class, then we call the method by the that reference, the method we called is the derived class' method. 
  3. Polymorphism is implemented at run time, since complier are unable to know with method to call, the solution is late binding or dynamic binding, it occurs at run time.
  4. All method binding in Java uses late binding unless the static and final(private methods are implicitly final).
  5. Polymorphism provide the convenience that changes in the code do not cause damage to parts of the program that should not be affected. It is an important technique for the programmer to separate the things that change from the things that stay the same.
  6. Private method can never be override, to be clear, use different name from a private method in base class.
  7. The fields and static method are not polymorphism, that is, if use base class references to access the static methods and fields, we are accessing the fields and static method in super class.
  8. If we have a field in derived class with the same name as the field in base class, it is allowed, but the field in super is hidden by the filed in derived class, if we want to access it, we should use super.field.

Constructor:
  1. The order constructor calls for a complex object is as follows:
    • The base class constructor is called. This step repeat recursively such that the root of hierarchy is constructed first, follow by the next derived class, until the most-derived class is reached.
    • Member are initialised in the order of declaration.
    • The body of the derived-class constructor is called.
  2. If we need to dispose, we need to dispose in the reverse order of construction. We first dispose the most-derived class, can do it recursively until reach the base class.
  3. If we call a dynamic bound method inside a constructor, the overridden definition for that method is also used, even we are at the base class.
  4. Covariant return type means the overridden method in derived class can return the type which derived from the return type in the base-class method.
  5. Substitution vs Extension
  6. Every downcast is checked in Java, if cannot be done, ClassCastException will be thrown.

No comments:

Post a Comment