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

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

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

7.4.3 对象职责

我们来重新回顾第1章中的Shape例子,请见图7.11。

图7.11 Shape类继承体系图

多态性是对继承的最优雅的使用之一。请记住Shape类是不能被实例化的。由于它有个抽象方法getArea(),所以它是一个抽象类。第8章将解释抽象类的细节。

不过Rectangle和Circle可以被实例化,因为它们是实实在在的类。尽管矩形和圆都是形状,但它们有不同之处。它们作为形状,可以计算各自的面积。而各自计算面积的公式是不同的。因此,计算面积的公式不能放置在Shape类中。

这就是多态性的由来。多态性的前提是你可以给不同的对象发送消息,而对象则会根据各自的类型进行响应。例如,如果你向Circle类发送getArea()消息,调用的计算方式与向Rectangle类发送相同的getArea()消息的计算方式是不同的。这是因为Circle和Rectangle拥有各自的响应方式。如果你让Circle返回其面积,它知道怎么做。如果你让圆绘制自身,它也知道怎么做。即使Shape对象可以被实例化,它也做不到这些,因为它缺乏对自身足够的信息。注意图7.11中的UML图,Shape类中的getArea()方法是斜体的。这表示了该方法是抽象方法。

假设如下一个简单的示例,我们有四个类:抽象类Shape,实体类Circle、Rectangle和Star。以下是代码:

注意每个类中只存在一个方法:draw()。以下是对象自身职责与多态性相关的重要一点,实体类自身负责实现绘制功能。Shape类并不提供绘制的代码,Circle,Rectangle和Star类需要各自实现绘制代码。以下是证明这一点的一些代码: ...

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