Skip to Content
面向对象的思考过程(原书第5版)
book

面向对象的思考过程(原书第5版)

by 马特 魏斯费尔德
August 2021
Intermediate to advanced
450 pages
4h 46m
Chinese
Pearson
Content preview from 面向对象的思考过程(原书第5版)

11.1.1 继承

不论你是否完全相信关于组合优于继承的说法,下面我们展示一个直接使用继承的例子,探索一下是否可以通过组合的方式实现。回顾在整本书里我们都提到过的哺乳动物的例子。在这里,我们加入一个新的可以飞的哺乳动物——蝙蝠,如图11.1所示。

图11.1 使用继承创建哺乳动物

在这个例子中,继承看起来是很明显的选择。从Mammal类继承创建一个Dog类是显而易见的。请看下面使用继承实现的代码。

在这个设计里,一个哺乳动物只有单个行为,eat(),假设所有的哺乳动物都必须进食。然而,当我们增加两个Mammal子类:Bat和Dog,就能看出继承的问题。虽然狗能走路,但并不是所有的哺乳动物能够走路。此外,蝙蝠虽然可以飞行,但其他的哺乳动物不一定能飞行。所以问题在于,这些方法要放在哪里?就像之前提到的企鹅的例子,并不是所有的鸟都会飞,所以如何在继承的层级里放置这些方法是非常棘手的。

将Mammal类拆分为FlyingMammals类和WalkingMammals类并不是一种优雅的解决方案,因为这只不过是冰山一角,一些哺乳动物可以游泳,一些甚至可以产卵。此外,对于单个种类哺乳动物可能有无数种行为,为每种行为都创建一个单独的类是不实际的。因此,比起用is-a这样的关系去设计,可能我们更应该使用has-a这样的关系。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Node与Express开发(第2版)

Node与Express开发(第2版)

Ethan Brown
手把手教会你linux

手把手教会你linux

桑德.范.乌格特
Java并发编程实战

Java并发编程实战

Brian Goetz, Tim Peierls

Publisher Resources

ISBN: 9787111684527