Polymorphism


  • The polymorphic method call allows one type to express its distinction from another, similar type, as long as they’re both derived from the same base type.

Upcasting revisited

  • Taking an object reference and treating it as a reference to its base type is called upcasting.

Forgetting the object type

  • The compiler won’t give you any error messages if you forget to overload one of your methods and the whole process of working with types becomes unmanageable.
  • Wouldn’t it be nice if you could forget that there are derived classes, and write your code to talk only to the base class?

The twist

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.
  • late binding means that the binding occurs at run time, based on the type of object.
  • There must be some mechanism to determine the type of the object at run time and to call the appropriate method.
  • All method binding in Java uses late binding unless the method is static or final(private methods are implicitly final).
  • Declaring a method final effectively “turns off” dynamic binding, or rather it tells the compiler that dynamic binding isn’t necessary.

Producing the right behavior

  • Once you know that all method binding in Java happens polymorphically via late binding, you can write your code to talk to the base class and know that all the derived-class cases will work correctly using the same code.

Extensibility

  • You can add new functionality by inheriting new data types from the common base class.
  • Changes in your code don’t cause damage to parts of the program that should not be affected.
  • Polymorphism is an important technique for the programmer to “separate the things that change from the things that stay the same.”

Pitfall: “overriding” private methods

  • A private method is automatically final, and is also hidden from the derived class.
  • Only non-private methods may be overridden.
  • You should watch out for the appearance of overriding private methods, which generates no compiler warnings.
  • You should use a different name from a private base-class method in your derived class.

Pitfall: fields and static methods

  • Only ordinary method calls can be polymorphic.
  • Any field accesses are resolved by the compiler, and are thus not polymorphic.
  • If a method is static, it doesn’t behave polymorphically.

Constructors and polymorphism

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

Order of constructor calls

  • A constructor for the base class is always called during the construction process for a derived class.

  • The constructor has a special job: to see that the object is built properly.

  • Only the base-class constructor has the proper knowledge and access to initialize its own elements.

  • It’s essential that all constructors get called; otherwise the entire object wouldn’t be constructed.

  • It will silently call the default constructor if you don’t explicitly call a base-class constructor in the derived-class constructor body.

  • The order of constructor calls:

    1.The base-class constructor is called.

    2.Member initializers are called.

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

  • You must be able to assume that all the members of the base class are valid when you’re in the derived class.

  • Inside the constructor, however, you must be able to assume that all members that you use have 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.

  • Whenever possible, you should initialize all member objects at their point of definition in the class.

Inheritance and cleanup

  • Most of the time you won’t have to worry about cleaning up.
  • The order of disposal should be the reverse of the order of initialization, in case one subobject is dependent on another.
  • This technique(reference counting) 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

  • If you call a dynamically-bound method inside a constructor, the overridden definition for that method is used.
  • The effect of this call can be rather unexpected because the overridden method will be called before the object is fully constructed.
  • 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.
  • In actual initialization, the storage allocated for the object is initialized to binary zero before anything else happens.
  • 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.

Covariant return types

  • An overridden method in a derived class can return a type derived from the type returned by the base-class method.

Designing with inheritance

  • It’s possible to dynamically choose a type (and thus behavior) when using composition, whereas inheritance requires an exact type to be known at compile time.
  • You can’t decide to inherit differently at run time; that must be completely determined at compile time.
  • Use inheritance to express differences in behavior, and fields to express variations in state.

Substitution vs. extension

  • pure substitution: derived class objects can be perfectly substituted for the base class.
  • The base class can receive any message you can send to the derived class because the two have exactly the same interface.
  • is-like-a” relationship: the derived class is like the base class—it has the same fundamental interface—but it

    has other features that require additional methods to implement.
  • The extended part of the interface in the derived class is not available from the base class, so once you upcast, you can’t call the new methods.

Downcasting and runtime type information

  • With a downcast, you don’t really know that a shape (for example) is actually a circle.
  • In Java, every cast is checked!
  • This act of checking types at run time is called runtime type identification (RTTI).
  • You can try to downcast. If it’s the correct type, it will be successful. Otherwise, you’ll get a ClassCastException.

Thinking in Java——笔记(8)的更多相关文章

  1. Effective Java笔记一 创建和销毁对象

    Effective Java笔记一 创建和销毁对象 第1条 考虑用静态工厂方法代替构造器 第2条 遇到多个构造器参数时要考虑用构建器 第3条 用私有构造器或者枚举类型强化Singleton属性 第4条 ...

  2. java笔记00-目录

    --2013年7月26日17:49:59 学习java已久,趁最近有空,写一个总结: java笔记01-反射:

  3. java笔记整理

    Java 笔记整理 包含内容     Unix Java 基础, 数据库(Oracle jdbc Hibernate pl/sql), web, JSP, Struts, Ajax Spring, E ...

  4. 转 Java笔记:Java内存模型

    Java笔记:Java内存模型 2014.04.09 | Comments 1. 基本概念 <深入理解Java内存模型>详细讲解了java的内存模型,这里对其中的一些基本概念做个简单的笔记 ...

  5. servlet(6) - servlet总结 - 小易Java笔记

    垂阅前必看: 这都是我总结的我觉得是学习servlet应该掌握的,我在学习期间也做了一个博客项目来让所学的知识得以巩固.下面就是博客项目链接.前面的servlet相关的笔记总汇,还有就是我把觉得在学习 ...

  6. Java笔记 —— 继承

    Java笔记 -- 继承 h2{ color: #4ABCDE; } a{ text-decoration: none!important; } a:hover{ color: red !import ...

  7. Java笔记 —— 方法重载和方法重写

    Java笔记 -- 方法重载和方法重写 h2{ color: #4ABCDE; } a{ text-decoration: none !important; } a:hover{ color: red ...

  8. Java笔记 —— 初始化

    Java笔记 -- 初始化 h2{ color: #4ABCDE; } a{ text-decoration: none !important; } a:hover{ color: red !impo ...

  9. Java笔记 —— this 关键字

    Java笔记 -- this 关键字 h2{ color: #4ABCDE; } a{ color: blue; text-decoration: none; } a:hover{ color: re ...

  10. Java 笔记 —— java 和 javac

    Java 笔记 -- java 和 javac h2{ color: #4ABCDE; } a{ text-decoration: none !important; } a:hover{ color: ...

随机推荐

  1. http://www.cnblogs.com/baizhanshi/p/5593431.html

    http://www.cnblogs.com/baizhanshi/p/5593431.html

  2. Codeforces Round #342 (Div. 2)

    贪心 A - Guest From the Past 先买塑料和先买玻璃两者取最大值 #include <bits/stdc++.h> typedef long long ll; int ...

  3. Android自动截屏小脚本

    @echo off echo * 截图文件将保存在 E:\pic下,以当前日期+时间命名. echo ================================================= ...

  4. XML Basic

    XML声明: <?xml version="1.0" encoding="UTF-8"?> XML中属性的value值要被引号(单引号or双引号)引 ...

  5. ccc 多点触控2

    经过不断的思考发现,如果是两个sprite都添加触控的时候,往往直接成单点触控, 但是如果是两个node的时候在node上面点击就会变成多点触控的形式 cc.Class({ extends: cc.C ...

  6. POJ 2407 (欧拉函数)

    题目链接: http://poj.org/problem?id=2407 题目大意:求小于n且与n互质的正整数个数. 解题思路: 欧拉函数=小于n且与n互质的正整数个数. 公式=n*(1-1/P1)* ...

  7. javac命令出现“**.java使用了未经检查或不安全的操作”

    Collection col=new ArrayList();引发了“**.java使用了未经检查或不安全的操作”错误, 这是因为JDK1.5中引进了泛型,但是你的ArrayList却没有采用,所有会 ...

  8. java开发_模仿百度文库_OpenOffice2PDF_注意事项

    在模仿百度文库的操作过程中,有很多朋友反映出来的一些问题,是我想起了写这篇blog. 主要是让大家在做的过程中注意一些东西,否则达不到想要的效果. 第一步:我们先从 java开发_模仿百度文库_Ope ...

  9. RSA_RSA算法原理(二)

    上一次,我介绍了一些数论知识. 有了这些知识,我们就可以看懂RSA算法.这是目前地球上最重要的加密算法. 六.密钥生成的步骤 我们通过一个例子,来理解RSA算法.假设爱丽丝要与鲍勃进行加密通信,她该怎 ...

  10. 项目管理gitflow的用法(转)

    在这里主要讲一下我在项目中用到的关于gitflow的用法.   公司的项目中,专门有一台用来存放版本库的服务器,路径是在默认的安装目录/opt/git/,那么在使用的时候,如果你是一个功能模块或者是一 ...