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程序设计
126
5
designing for inheritance
子类应该覆盖什么
接下来,我们需要考虑
animal
子类应该覆盖哪些属性和方法。我
们从属性开始。
动物们有不同的属性值
Animal父类有imagefoodhabitathunger属性,所有
这些属性都被animal子类继承。
所有的动物看起来都不同,生活在不同的栖息地,并有不同的
饮食要求。这意味着我们应覆盖imagefoodhabitat
性,这样对于每种动物进行了不同的初始化。例如,我们可以
Hippohabitat属性值初始化为“
water
”,Lionfood
属性初始化为“
meat
”。
Animal
image
food
habitat
hunger
makeNoise()
eat()
roam()
sleep()
不同的方法实现
每个动物子类都从Animal父类继承了makeNoiseeatroam
以及sleep方法。那么我们可以覆盖哪些方法呢?
狮子咆哮,狼嚎叫,河马咕噜。所有动物都会发出不同的声响,
这意味着我们应该覆盖每个动物子类中的makeNoise方法。每
个子类仍将包含makeNoise方法,但该方法的实现因动物而有
所不同。
类似地,每个动物都会进食,但进食的方式有所不同。例如,
河马在草地上吃草,而猎豹捕食猎物。为了适应这些不同的进
食习惯,我们覆盖每个动物子类中的eat方法。
确定子类是否需要特定的默认属性
值或方法实现
在本例中,我们将覆盖imagefood
habitat属性,以及makeNoise
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