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

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

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

3.1 构造函数

构造函数对于结构化编程的程序员来说是个新概念。非面向对象的语言(比如COBOL、C和Basic)通常不会用到构造函数。C/C++中的结构体(struct)具有构造函数。在前两章中,我们提到过这个用于构造对象的特殊方法。在诸如Java和C#之类的面向对象的语言中,构造函数是名称与类名相同的方法。而Visual Basic .NET使用指定的名称New,Swift使用init关键字。通常这里我们只关注构造函数概念,而不会介绍所有语言的特殊语法。接下来用Java代码来实现一个构造函数。

例如,第2章中的Cabbie类的构造函数如下所示:

编译器会意识到这个方法名与类名完全相同,所以认为该方法是个构造函数。

小心

注意Java代码(以及C#和C++)中,构造函数没有返回值。如果有返回值,编译器就不认为该方法是构造函数。

例如,如果类中有以下代码,那么编译器不会认为该方法是构造函数,因为它有返回值,这个返回值是一个整数:

该语法要求会导致问题,因为这段代码可以编译,但却得不到期望的行为。

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