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

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

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

7.2 继承

第1章已经对继承做了定义,即子类可以从父类中继承属性和行为。这里我们会进一步讨论继承,探索有关继承的更多细节。

第1章指出,可以用一个简单的规则来确定继承关系:如果类B是(is a)类A,那么该关系很可能就是继承关系。

is-a

面向对象设计的主要规则之一就是公共继承代表了is-a关系。至于接口,你可以增加“behaves like”关系(实现接口)。继承来的数据(属性)是“is”,描述已封装行为的接口是“acts like”关系,而组合是“has a”关系。各种关系之间的边界变得越来越模糊。

我们再回顾一下第1章中的哺乳动物示例。有一个Dog类。狗拥有一些行为来证明它是一条狗,从而与猫区别开来。本例中指定了两个行为,狗会吠叫(bark),也会喘粗气(pant)。所以我们创建了一个名为Dog的类,该类包含了这两个行为,而且具有两个属性(如图7.1所示)。

图7.1 Dog类的类图

接下来我们想创建一个GoldenRetriever(金毛猎犬)类。我们可以创建一个新类,具有Dog类的相同行为。然而,我们可以得出一个合理的结论,金毛猎犬是狗。基于这样的关系,我们可以从Dog类中继承属性和行为,从而在新的GoldenRetriever类中使用它们。如图7.2所示。

GoldenRetriver类既包含了普通狗的行为,也拥有自己的特有行为。这给我们提供了很多便利。首先,在编写GoldenRetriever类时,我们不需要重新发明轮子来编写bark和pant方法。这不仅节省了设计和编码时间,而且节省了测试及维护时间。只需编写一次bark和pant方法,而且假设当编写Dog类时我们已经进行了正确测试,这样就无须再次测试。但是对于新接口还是需要重新测试。 ...

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