Skip to Content
Head First Kotlin程序设计
book

Head First Kotlin程序设计

by Dawn Griffiths, David Griffiths
August 2020
Intermediate to advanced
483 pages
11h 24m
Chinese
China Machine Press
Content preview from Head First Kotlin程序设计
你现在的位置 4 95
classes and objects
对象
Dog
name
weight
breed
bark()
如何创建
Dog
对象
var myDog = Dog("Fido", 70, "Mixed")
我们将使用Dog类创建一个Dog对象,并且将其赋值给名为myDog
变量。代码如下:
该代码将三个参数值传给了Dog对象。这些参数值与我们定义Dog
的属性相匹配:Dognameweight以及breed
class Dog(val name: String, var weight: Int, val breed: String) {
...
}
代码运行时会创建一个新的Dog对象,并且使用这三个参数值为该
对象的属性赋值。在我们的例子中,我们正在创建一个新的Dog
对象,其name为“
Fido
”、weight属性为
70
磅,而breed属性
为“
mixed
”。
你可以将类想象成一个对象的模板,因为它告诉编译器如何创建该
特定类的对象。它还将告诉编译器每个对象应该具有哪些属性,并
且从该类生成的每个对象都可以拥有自己独有的属性值。例如,每
Dog对象都有自己的名称、重量和品种属性,每个Dog的属性值都
可以是不同的。
Dog
name
weight
breed
bark()
一个类
现在你已经知道如何创建一个新的Dog对象。接下来,我们将介绍
如何访问属性和函数。
多个对象
你通过传入三个属性参数
创建了
D
og
对象
var Dog
Dog
name: “Fido”
weight: 70
breed: “Mixed” ...
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

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

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

马特 魏斯费尔德
GraphQL 学习指南

GraphQL 学习指南

Eve Porcello, Alex Banks
前端架构设计

前端架构设计

Micah Godbolt

Publisher Resources

ISBN: 9787111662358