Skip to content

Inheritance

Java for AP CS A Lesson 17 1:59 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
Inheritance lets one class build on another instead of copying it. 继承让一个类在另一个类的基础上搭建,而不是把代码抄一遍。
Animal has a name and a speak method; Dog and Cat extend Animal, so they get both for free and only write what is different. Animal 有一个 name 和一个 speak 方法; Dog 和 Cat 继承 Animal, 所以这两样它们白拿,只需要写出不一样的部分。
Notice the arrows: they point from the subclass UP to the class it extends. 注意那些箭头:它们从子类"向上"指向被继承的类。
That is the direction inheritance goes, and drawing it the other way round is a common slip. 这就是继承的方向, 而把它画反是很常见的失误。
A subclass constructor has to get the inherited part built, and that is what super does. 子类的构造器必须先把"继承来的那部分"建好,而这正是 super 干的事。
Call super with the arguments the parent constructor wants, and the parent sets up its own part; only then do the subclass's own lines run. 用父类构造器需要的参数去调用 super, 父类就把属于自己的那一部分安置好; 之后子类自己的那些行才开始跑。
And there is a hard rule: super must be the very first line of the constructor. 而且有一条硬规矩: super 必须是构造器的"第一行"。
Writing a method in the subclass with the same name and parameters overrides it — the subclass's version replaces the parent's, and Dog prints Woof. 在子类里写一个同名、同参数的方法,就是"重写"—— 子类的版本替换掉父类的,于是 Dog 打印 Woof。
Sometimes you want to keep what the parent did and add to it, and then you call super dot speak first to run the parent's version too. 有时候你想保留父类做的事,再在上面加一点, 那就先调用 super.speak(),把父类的版本也跑一遍。
Same call site, two lines of output. 调用的地方一模一样,输出却变成了两行。
And here is why any of this is useful. 而这一切之所以有用,原因在这里。
A Dog IS an Animal, so a Dog can be stored in an Animal variable, put in an Animal array, passed to a method that takes an Animal, and returned from one. 一条 Dog "就是"一个 Animal, 所以 Dog 可以存进 Animal 变量、放进 Animal 数组、 传给接收 Animal 的方法,也可以被这样的方法返回。
A subclass fits anywhere an Animal is expected — which is what makes the next lesson possible. 子类可以出现在任何"期待一个 Animal"的地方—— 而这正是下一课得以成立的前提。
Four things to take with you. 带走四点。
One: extends makes a subclass that inherits the rest. 第一:extends 建立一个继承其余部分的子类。
Two: super in a constructor must be the first line. 第二:构造器里的 super 必须写在第一行。
Three: super dot method extends instead of replacing. 第三:super.方法 是在扩展,而不是替换。
Four: a subclass fits wherever its superclass is expected. 第四:子类可以出现在任何期待其父类的地方。
Now build a small hierarchy in the task below. 现在去下面的题里搭一个小的继承层次。

Log in or create account

IGCSE, A-Level & AP