Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(八)之Polymorphism
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的更多相关文章
- 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 ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(七)之Access Control
Access control ( or implementation hiding) is about "not getting it right the first time." ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(六)之Initialization & Cleanup
Two of these safety issues are initialization and cleanup. initialization -> bug cleanup -> ru ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十三)之Strings
Immutable Strings Objects of the String class are immutable. If you examine the JDK documentation fo ...
- 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 ...
- 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 ...
- 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 ...
- 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 ...
- 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 ...
随机推荐
- 翻转-Flip Columns For Maximum Number of Equal Rows
2020-02-20 11:00:06 问题描述: 问题求解: 翻转题一个常见的思路就是站在结束的状态来反推最初的状态,本题的解题思路就是站在结束的时候的状态来进行反推. 如果在最终的状态i-row是 ...
- 李宏毅老师机器学习课程笔记_ML Lecture 1: ML Lecture 1: Regression - Demo
引言: 最近开始学习"机器学习",早就听说祖国宝岛的李宏毅老师的大名,一直没有时间看他的系列课程.今天听了一课,感觉非常棒,通俗易懂,而又能够抓住重点,中间还能加上一些很有趣的例子 ...
- angular中$q用法, $q多个promise串行/同步/等待), $q.all用法,使用
$q的基本用法 function fn() { var defer = $q.defer(); setTimeout(function () { console.log(1); defer.resol ...
- 主从校验工具pt-table-checksum和pt-table-sync工作原理
pt-table-checksum和pt-table-sync是常用来做MySQL主从数据一致性校验的工具,pt-table-checksum只校验数据,不能对数据进行同步:pt-table-sync ...
- prometheus远程写参数优化
一.概述 prometheus可以通过远程存储来解决自身存储的瓶颈,所以其提供了远程存储接口,并可以通过过配置文件进行配置(prometheus.yml).一般情况下我们使用其默认的配置参数,但是为了 ...
- OpenCV-Python 模板匹配 | 三十一
目标 在本章中,您将学习 使用模板匹配在图像中查找对象 你将看到以下功能:cv.matchTemplate(),cv.minMaxLoc() 理论 模板匹配是一种用于在较大图像中搜索和查找模板图像位置 ...
- PHP7内核(五):系统分析生命周期
上篇文章讲述了模块初始化阶段之前的准备工作,本篇我来详细介绍PHP生命周期的五个阶段. 一.模块初始化阶段 我们先来看一下该阶段的每个函数的作用. 1.1.sapi_initialize_reques ...
- IEnumerable和IQueryable在使用时的区别
最近在调研数据库查询时因使用IEnumerable进行Linq to entity的操作,造成数据库访问缓慢.此文讲述的便是IEnumerable和IQueryable的区别. 微软对IEnumera ...
- Linux上的软件安装有哪些方式?
Linux上的软件安装有以下几种常见方式介绍 1.二进制发布包 软件已经针对具体平台编译打包发布,只要解压,修改配置即可 2.RPM包 软件已经按照redhat的包管理工具规范RPM进行打包发布,需要 ...
- Python——交互式图形编程
一. 1.图形显示 图素法 像素法 图素法---矢量图:以图形对象为基本元素组成的图形,如矩形. 圆形 像素法---标量图:以像素点为基本单位形成图形 2.图形用户界面:Graphical User ...