Lec 10 - Subtype Polymorphism vs. HoFs
这一章真的很绕。
Dynamic Method Selection Puzzle

首先看这样一个问题。答案是除了最后一个o3.bark()会报错,其他都调用的ShowDog()的bark()。后者是因为dynamic type均为ShowDog,前者需要仔细说一下。
上回书说道:如Object o3 = (Dog) o2;这种形式的casting,不改变compile-time type。这里这个不改变,是对等号两端均无改变(compile-time type的定义中就说了它永远不会变)。所以,o3的compile-time type仍为Object,dynamic type为ShowDog。当call bark() method时,发现Object中并无此方法,故报错 (Compiler allows calls based on static type)。
static方法不能Override(还没想明白为什么)
Subtype Polymorphism vs. Explicit HoFs

Polymorphism: providing a single interface to entities of different types
如上图,deque的compile-time type是deque,不管他的run-time type是什么,比如LinkedDeque或者ArrayDeque,deque.addFirst()都会根据当前run-time type,实现相同的功能。这就是Polymorphism。

Application 1: Comparables
DIY OurComparable

Josh想建一个对任何array都适用的max()方法,发现不好整。如上图,运行到if (items[i] > items[maxDex])这里会出错,因为两个Object怎么比大小呢?比的应该是Dod的size才对,这咋整呢?
对任何都适用,是不是想到了以前学过的interface inheraitance?
- Step 1,建立一个interface
public interface OurComparable {
/** Return nagtive if this < o
* Return 0 if this = o
* Return positive if this > o
*/
public int compareTo(Object o);
}
需要有一个方法compareTo,实现比较类大小的功能。
Object o也可变为OurComparable o,因为只有继承OurComparable的类才能进行比较。
- Step 2, 让Dog继承,并编写compareTo方法具体实现
public class Dog implements OurComparable {
private String name;
private int size;
public Dog(String n, int s) {
name = n;
size = s;
}
public void bark() {
System

本文深入探讨了子类型多态与高阶函数在动态方法选择、比较器和可比较对象中的应用,解释了Java中如何通过实现Comparable接口达到泛型比较的目的,并介绍了Comparator接口用于更灵活的排序策略。
最低0.47元/天 解锁文章
4177

被折叠的 条评论
为什么被折叠?



