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 ...
随机推荐
- eclipse、 IDEA中字母大小写转换快捷键
eclipse 中字母大小写切换快捷键: ctrl + shift + x 转为大写 ctrl + shift + y 转为小写 IDEA 中字母大小写切换快捷键: ctr + sh ...
- 【2019牛客暑期多校第三场】J题LRU management
题目链接 题意 好吧,这道题我其实看都没看过,队友跟我说了说这道题是模拟题,卡时间.然后我就上了-- 大致就是维护一个线性表,然后有两种操作:插入.查询 插入时,如果这个值(string)之前出现过, ...
- 十分钟一起学会Inception网络
作者 | 荔枝boy 编辑 | 安可 一.Inception网络简介 二.Inception网络模块 三.Inception网络降低参数计算量 四.Inception网络减缓梯度消失现象 五.Ince ...
- 寻找一把进入 Alibaba Sentinel 的钥匙(文末附流程图)
经过前面几篇文章的铺垫,我们正式来探讨 Sentinel 的 entry 方法的实现流程.即探究进入 Alibaba Sentinel 核心的一把钥匙. @ 目录 1.SphU.entry 流程分析 ...
- 4 Values whose Sum is 0 POJ - 2785(二分应用)
题意:输入一个数字n,代表有n行a,b,c,d,求a+b+c+d=0有多少组情况. 思路:先求出前两个数字的所有情况,装在一个数组里面,再去求后两个数字的时候二分查找第一个大于等于这个数的位置和第一个 ...
- 3分钟学会简单使用Vim
Vim是一款运行在命令行里的文字编辑器,它是Linux人员的标配.在Windows环境下也可以有特别的用处,比如创建没有文件名的文件(.gitignore). Vim的功能十分强大,以至于有一些人对它 ...
- nosql Redis命令操作详解
Redis命令操作详解 一.key pattern 查询相应的key (1)redis允许模糊查询key 有3个通配符 *.?.[] (2)randomkey:返回随机key (3)type key: ...
- javascript实现炫酷魔方
实现效果: 魔方动态转换,同时每个面里的每个块都能进行动态变换. 实现代码: <!DOCTYPE html> <html> <head> <meta char ...
- 值传递:pass by value(按值传递) 和 pass by reference(引用传递)-[all]-[编程原理]
所有的编程语言,都会讨论值传递问题. 通过一个js示例直观认识 //理解按值传递(pass by value)和按引用传递(pass by reference) //pass by value var ...
- Light of future-凡事预则立
目录 1.冲刺的时间计划安排 2.针对上一次作业同学.助教提出的问题的回答 3.针对前几次作业的不足的地方进行思考和总结 4.需要改进的团队分工 5.团队的代码规范 6.Github仓库链接 归属班级 ...