Polymorphism is the third essential feature of an object-oriented programming language,after data abastraction and inheritance.

It provides another dimension of separation of interface from implementation, to decouple what from how. Polymorphism allows improved code organization and readability as well as the creation of extensible programs that can be "grown" not only during the original creation of the project, but also when new features are desired.

Polymorphism deals with decoupling in terms of types.

Polymorphism also called dynamic binding or late binding or run-time binding

Upcasting revisited

  Forgetting the object type

  The compiler can't know that this Instrument reference points to a Wind in the case and not a Brass or Stringed.

  Method-call binding

  Connecting a method call to a method body is called binding. When binding is performed before the program is run ( by the compiler and linker, if there is one), it's called early binding.  C compilers have only early binding.

  The solution is called late binding, which means that the binding occurs at run time, based on the type of object. Late binding is also called dynamic binding or runtime binding.

  That is, the compiler still doesn't know the object type, but the method-call mechanism finds out and calls the correct method body. ( you can imagine that som 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 methods are implicitly final). This means that ordinarily you don't need to make any decisions about whether late binding will occur--it happens automatically

  only use finla as a design decision, and not as an attempt to improve performance.

  Producing the right behavior

  Extensibility

  Polymorphism is an important technique for the programmer to "separate the things that change from the thins that stay the same."

  Pitfall: "overriding" private methods

  public class PrivateOverride {

    private void f() {print("private f()");}

    public static void main (String[] args) {

      PrivateOverride po = new Derived();

      po.f();

    }

  }

  class Derived extends PrivateOverride {

    public void f() { print("public f()");}

  }

  输出: private f()

  Derived's f() in this case is a brand new method; it's not even overloaded,since the base-class version of f() isn't visible in Derived.

  Pitfall: fields and static methods

  only ordinary method calss can be polymorphic

  For example, if you acces a field directly, that access will be resolved at compile time.

  When a Sub object is upcast to a Super reference, any field accesses are resolved by compiler, and are thus not polymorphic. In this example, different storage is allocated for Super.field and Sub.field. Thus, Sub actually contains two fieldss called field: its own and the one that it gets from Super. Howerver, the Super version in not the default that is produced when refer to field in Sub; in order to get the Super field you must explicitly say super.field.

  Although this seems like it could be a confusing issue, in practive it virtually 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 a base-class field and a derived-class field, because its confusing.

Constructors and polymorphism

  Constructors are not polymorphic (they're actually static methods, but the static declaration is implicit).

  Order of constructor calls

  Inheritance and cleanup

  If you do have cleanup issues, you must be diligent and create a dispose() method for you new class. And with inheritance, you must override dispose() in the derived class if you have any special cleanup that must happen as part of garbage collection. When you override dispose() in an inherited class, it's important to remember to call the base-class version of dispose(), since otherwise the base-class cleanup will no happen.

  If one of the member objects is shared with one or more other objects, the problem becomes more complex and you cannot simply assume that you can call dispose(). In this case, reference counting may be necessary to keep track of the number of objects that are still accessing a shared object.

  private int refcount = 0;

  public void addRef() { refcount++;}

  protectd void dispose(){

    if ( -- refcount == 0){

      // 具体的dispose

    }

  When you attach a shared object to your class, you must remember to call addRef(), but the dispose() method will keep track of the reference count and decide when to actually perform the cleanup. This technique requires extra diligence to use, but if you are sharing objects that require cleanup you don't have much choice.

  Behavior of polymorphic methods inside constructors

class Glyph {
  void draw() { print("Glyph.draw()"); }
  Glyph() {
    print("Glyph() before draw()");
    draw();
    print("Glyph() after draw()");
  }
}
class RoundGlyph extends Glyph {
  private int radius = 1;
  RoundGlyph(int r) {
    radius = r;
    print("RoundGlyph.RoundGlyph(), radius = " + radius);
  }
  void draw() {
    print("RoundGlyph.draw(), radius = " + radius);
  }
}
public class PolyConstructors {
  public static void main(String[] args) {

    new RoundGlyph(5);
  }
} /* Output:
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5

  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.)

Convariant return types

  Java SE5 adds convariant 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

  If you choose inheritance first when you're using an existing class to make a new class, things can become needlessly complicated.

  A better approach is to choose composition first, especially when it's not obvious which one you should use.

  A general guideline is " Use inheritance to express difference in behavior, and fields (composition) to express variations in state."

  Substitution vs. extension

  It would seem that the cleanest way to create an inheritance hierarchy is to take the "pure" approach. That is , only methods that have been established in the base class are overridden in the derived class.

  All you need to do is upcast from the derived class and never look back to see what exact type of object you're dealing with. Everything is handled through polymorphism.

  This too is a trap. Extending the interface is the perfect solution to a particular problem. This can be termed an "is-like-a" relationship.

  Downcasting and runtime type information

  At run time this cast is checked to ensure that it is in fact the type you think it is. If it isn't, you get a ClassCastException.

  The act of checking types at run time is called runtime type identification (RTTI).

Summary

  

Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(八)之Polymorphism的更多相关文章

  1. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(八)之Reusing Classes

    The trick is to use the classes without soiling the existing code. 1. composition--simply create obj ...

  2. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(七)之Access Control

    Access control ( or implementation hiding) is about "not getting it right the first time." ...

  3. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(六)之Initialization & Cleanup

    Two of these safety issues are initialization and cleanup. initialization -> bug cleanup -> ru ...

  4. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十三)之Strings

    Immutable Strings Objects of the String class are immutable. If you examine the JDK documentation fo ...

  5. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(二)之Introduction to Objects

    The genesis of the computer revolution was a machine. The genesis of out programming languages thus ...

  6. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十四)之Type Information

    Runtime type information (RTTI) allow you to discover and use type information while a program is ru ...

  7. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十二)之Error Handling with Exceptions

    The ideal time to catch an error is at compile time, before you even try to run the program. However ...

  8. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十一)之Holding Your Objects

    To solve the general programming problem, you need to create any number of objects, anytime, anywher ...

  9. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十)之Inner Classes

    The inner class is a valuable feature because it allows you to group classes that logically belong t ...

随机推荐

  1. Untargeted lipidomics reveals specific lipid abnormality in nonfunctioning human pituitary adenomas 非靶向脂质组学揭示非功能人类脑垂体瘤中的特异性脂质 (解读人:胡丹丹)

    文献名:Untargeted lipidomics reveals specific lipid abnormality in nonfunctioning human pituitary adeno ...

  2. eclipse操作快捷键

    Eclipse最全快捷键,熟悉快捷键可以帮助开发事半功倍,节省更多的时间来用于做有意义的事情. Ctrl+1 快速修复(最经典的快捷键,就不用多说了) Ctrl+D: 删除当前行 Ctrl+Alt+↓ ...

  3. 补充《解析“60k”大佬的19道C#面试题(上)》

    [广州.NET技术俱乐部]微信群的周杰写了一篇文章<解析“60k”大佬的19道C#面试题(上)>https://www.cnblogs.com/sdflysha/p/20200325-19 ...

  4. nop 配置阿里cdn 联通4g 页面显示不全 查看源代码发现被截断

    开发中遇见特别诡异的问题, 项目使用nop框架,pavilion主题,之后配置阿里cdn,然后在联通4g的情况下苹果手机网页显示不完全,nop首页和产品详情页都是如此,排查过程: 1.阿里cdn设置了 ...

  5. leetcode 945. 使数组唯一的最小增量

    题目 给定整数数组 A,每次 move 操作将会选择任意 A[i],并将其递增 1. 返回使 A 中的每个值都是唯一的最少操作次数. 示例 1: 输入:[1,2,2] 输出:1 解释:经过一次 mov ...

  6. 【笔记3-26】Python语言基础

    编译型语言和解释型语言 编译型语言 C 先编译 解释型语言 Python 边执行边编译 Python的介绍 吉多·范罗苏姆 1991 解释型语言 Life is short you need Pyth ...

  7. CUDA编程入门

    CUDA是一个并行计算框架.用于计算加速.是nvidia家的产品.广泛地应用于现在的深度学习加速. 一句话描述就是:cuda帮助我们把运算从cpu放到gpu上做,gpu多线程同时处理运算,达到加速效果 ...

  8. NSObject常用方法

    类 @interface NSObject <NSObject> { Class isa OBJC_ISA_AVAILABILITY; } // 初始化加载 + (void)load; / ...

  9. 浅谈C#中Tuple和Func的使用

    为什么将Tuple和Func混合起来谈呢? 首先,介绍一下:Tuple叫做元组,是.Net Framwork4.0引入的数据类型,用来返回多个数值.在C# 4.0之前我们函数有多个返回值,通常是使用r ...

  10. 在MVC三层项目中如何使用Log4Net

    --前期准备(添加到队列中) 0-1在新建后的MVC项目中的[Models]中添加一个类,用于处理异常信息,并继承自HandleErrorAttribute public class MyExcept ...