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

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

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

1.9.2 抽象

继承树可能会增长得非常庞大。当Mammal和Cat类完成后,可以快速添加其他哺乳动物(比如狗,或者狮子、老虎和熊)。Cat类也可以作为其他类的父类,比如作为波斯猫、暹罗猫等猫的父类。而Dog类也可以作为德国牧羊犬和鬈毛狗的父类(见图1.15)。继承的力量在于它的抽象和组织技术。

图1.15 Mammal UML图

太多的抽象层是很多开发者对于使用继承的谨慎的原因。常见的情况下,我们很难决定要抽象到什么程度。比如说,企鹅是鸟类,鹰也属于鸟类,它们是否应该都继承自一个带有fly方法的Bird类呢?

在大多数最新的面向对象的语言中(比如Java、.Net和Swift),一个类只能有一个父类,然而一个类可以有多个子类。另一些语言中,比如C++可以拥有多个父类。前一种情况称为单继承,后一种情况称为多重继承。

多重继承

考虑到一个孩子继承双亲的特征。那么这个孩子的眼睛应该继承自谁?这对于编译器来说是个非常重要的问题。C++允许多重继承,很多语言则不允许。

请注意GermanShepherd(德国牧羊犬)类和Poodle(鬈毛狗)类都继承自Dog类。每个类只有一个方法。然而由于它们继承自Dog,所以它们也继承自Mammal。即GermanShepherd和Poodle类获取了Dog和Mammal中所有的属性和方法,同时也拥有它们自身的属性和方法(如图1.16所示)。

图1.16 Mammal继承体系图

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

桑德.范.乌格特
Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉

Publisher Resources

ISBN: 9787111684527