Polymorphism
Java for AP CS A Lesson 18 1:44 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Here is the idea, and it is worth watching rather than reading.
这就是那个想法,而它值得"看",不太值得"读"。
The variable is declared as an Animal, and it points at a Dog.
这个变量声明的类型是 Animal,而它指向一条 Dog。
Call a dot speak and you get Woof.
调用 a.speak(),你得到 Woof。
Now point it at a Cat instead — the declaration has not changed at all, the call has not changed at all, and the answer is Meow.
现在改成让它指向一只 Cat—— 声明一点没变,调用也一点没变, 而答案变成了 Meow。
Java chose the method from the object, at run time.
Java 是"从对象"挑出方法的,而且是在运行时挑的。
That is dynamic dispatch.
这就是动态分派。
And this is what it buys you.
而这就是它换来的东西。
An array declared as Animals can hold a Dog, a Cat and a Cow.
一个声明为 Animal 的数组,可以装一条 Dog、一只 Cat 和一头 Cow。
One loop, one call, and each object answers for itself — a different line each time.
一个循环,一次调用,每个对象各自作答—— 每次都是不一样的一行。
There is no if, no instanceof, no switch.
没有 if,没有 instanceof,也没有 switch。
Add a fourth animal tomorrow and there is no change to this loop at all.
明天再加第四种动物,这个循环一个字都不用改。
One place you have already met this without knowing.
有一个地方,你其实早就用过它,只是没意识到。
Every class in Java inherits from Object, and Object has a toString.
Java 里每一个类都继承自 Object,而 Object 有一个 toString。
That is why printing any object works at all — and why, if nobody overrides it, what you get is the class name and a memory address.
这就是为什么打印"任何"对象都能work—— 也是为什么,如果没人重写它, 你拿到的就是类名加一串内存地址。
Override toString and every println of that object improves at once.
重写了 toString,这个对象的每一次 println 都立刻变好看了。
Four things to take with you.
带走四点。
One: the declared type is on the variable.
第一:声明类型在变量上。
Two: the actual type is the object it points at.
第二:实际类型在它所指向的那个对象上。
Three: the actual object picks the method, at run time.
第三:由那个实际的对象来挑方法,而且是在运行时挑。
Four: override toString or you print a memory address.
第四:重写 toString,否则你打印出来的是一串内存地址。
Now write a polymorphic loop in the task below.
现在去下面的题里写一个多态的循环。