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

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

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

8.3.3 综合运用

如果抽象类和接口都提供抽象方法,那么两者真正的区别是什么?正如我们之前看到的一样,抽象类可以提供抽象方法,也可以提供实体方法,而接口只能提供抽象方法。为什么会有这样的区别呢?

假设我们想设计一个类代表一条狗,稍后还想添加更多的哺乳动物。那么逻辑上应该创建一个名为Mammal的抽象类:

该类拥有一个实体方法叫作generateHeat(),还有一个抽象方法叫做makeNoise()。generateHeat()是个实体方法,因为所有的哺乳动物有体温。而makeNoise()方法是抽象的,因为每个动物的叫声是不同的。

我们创建一个名为Head的类,用于组合关系中:

Head有两个方法:getSize()和setSize()。尽管组合不能清晰地阐明抽象类和接口之间的区别,但本例中使用组合可以说明在面向对象系统的整体设计中如何一起使用抽象类和接口。我认为这很重要,因为这是一个完整的示例。请记住有两种方式来构建对象关系:继承表示is-a关系,组合表示has-a关系。问题是,接口适合哪种关系?

为了回答该问题,并且引入多种对象关系,我们来创建一个名为Dog的类,该类是Mammal的子类,实现了Nameable接口,并且有一个Head对象(如图8.5所示)。

简单来说,Java和.NET中有三种方式构建对象:分别是继承、接口及组合。注意图8.5中的虚线代表了接口。该例子演示了如何使用这些方式,什么时候选择抽象类,什么时候选择接口以及什么时候选择组合。我们来进一步探索。 ...

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