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

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

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

1.8.1 接口

我们可以看到接口定义了对象之间通信的基本方式。每个类设计接口规格来保证对象能被正确实例化和操作。必须向对象提供的接口发送消息来使用对象暴露的任何行为。接口需要完整描述类与类之间的交互。在大多数面向对象的语言中,访问修饰符指定为public的方法属于接口。

私有数据

为了实现数据隐藏,必须将所有属性声明为private。属性绝不是接口的一部分。只有公共方法是类接口的一部分。将属性描述为public破坏了数据隐藏这一理念。

我们在回过头看一个刚提到的例子,计算一个数字的平方值。在这个例子中,接口由两部分组成:

·如何实例化一个Square对象

·如何传递给该对象一个值,并获取返回的平方值结果

正如在本章前面讨论的一样,如果用户需要访问一个属性,我们会创建一个方法(即取值方法)来返回该属性值。如果用户想要获取该属性值,只需调用取值方法即可。在这种方式中,拥有该属性的对象可以控制访问该属性。这种控制非常重要,特别对安全、测试和维护而言。如果你可以控制对属性的访问,当出现了问题,无须追踪所有可能修改了该属性的代码片段,我们只需要修改一个地方(即赋值方法)。

基于安全的原因,你需要防止不受控的代码对例如密码和个人信息等数据进行修改和获取。例如,当你在使用ATM的时候,获取数据的权限通过PIN做了控制。

签名——类接口与方法接口

不要为用来扩展类的方法接口感到困惑。我会把这些通过方法代表的接口等同于“签名”。

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