An earlier chapter introduced you to the basics of defining and using classes in Kotlin. Classes are used to support traditional object-oriented programming.
Classes concepts include inheritance, overriding, polymorphism and composition which makes them suited for this purpose. These extra features require special consideration for construction, class hierarchies, and understanding the class lifecycle in memory.
This chapter will introduce you to the finer points of classes in Kotlin, and help you understand how you can create more complex classes.
Introducing inheritance
In the earlier chapter, you saw a Grade class and a pair of class examples: Person and Student.
data class Grade(val letter: Char, val points: Double, val credits: Double)
class Person(var firstName: String, var lastName: String) {
fun fullName() = "$firstName $lastName"
}
class Student(var firstName: String, var lastName: String,
var grades: MutableList<Grade> = mutableListOf<Grade>()) {
fun recordGrade(grade: Grade) {
grades.add(grade)
}
}
It’s not difficult to see that there’s an incredible amount of redundancy between Person and Student. Maybe you’ve also noticed that a Studentis a Person!
This simple case demonstrates the idea behind class inheritance. Much like in the real world, where you can think of a student as a person, you can represent the same relationship in code by replacing the original Person and Student class implementations with the following:
open class Person(var firstName: String, var lastName: String) {
fun fullName() = "$firstName $lastName"
}
class Student(firstName: String, lastName: String,
var grades: MutableList<Grade> = mutableListOf<Grade>())
: Person(firstName, lastName) {
open fun recordGrade(grade: Grade) {
grades.add(grade)
}
}
In this modified example, thePerson class now includes the open keyword, and the Student class now inherits from Person, indicated by a colon after the naming of Student, followed by the class from which Student inherits, which in this case is Person. The open keyword means that the Person class is open to be inherited from; the need for open is part of the Kotlin philosophy of requiring choices such as inheritance to be explicitly defined by the programmer.
You must still add parameters such as firstName to the Student constructor, and they are then passed along as arguments to the Person constructor. Notice in the modified example that the var keyword is no longer needed on the parameters, since they are already defined as properties in the Person class.
Through inheritance, Student automatically gets the properties and methods declared in the Person class. In code, it would be accurate to say that a Studentis-aPerson.
With much less duplication of code, you can now create Student objects that have all the properties and methods of a Person:
val john = Person(firstName = "Johnny", lastName = "Appleseed")
val jane = Student(firstName = "Jane", lastName = "Appleseed")
john.fullName() // Johnny Appleseed
jane.fullName() // Jane Appleseed
Additionally, only the Student object will have all of the properties and methods defined in Student:
val history = Grade(letter = 'B', points = 9.0, credits = 3.0)
jane.recordGrade(history)
// john.recordGrade(history) // john is not a student!
A class that inherits from another class is known as a subclass or a derived class, and the class from which it inherits is known as a superclass or base class.
The rules for subclassing are fairly simple:
A Kotlin class can inherit from only one other class, a concept known as single inheritance.
A Kotlin class can only inherit from a class that is open.
There’s no limit to the depth of subclassing, meaning you can subclass from a class that is also a subclass, like below (and first redefining Student with open):
open class Student(firstName: String, lastName: String,
var grades: MutableList<Grade> = mutableListOf<Grade>())
: Person(firstName, lastName) {
open fun recordGrade(grade: Grade) {
grades.add(grade)
}
}
open class BandMember(firstName: String,lastName: String) : Student(firstName, lastName) {
open val minimumPracticeTime: Int
get() { return 2 }
}
class OboePlayer(firstName: String, lastName: String): BandMember(firstName, lastName) {
// This is an example of an override, which we’ll cover soon.
override val minimumPracticeTime: Int = super.minimumPracticeTime * 2
}
A chain of subclasses is called a class hierarchy. In this example, the hierarchy would be OboePlayer → BandMember → Student → Person. A class hierarchy is analogous to a family tree. Because of this analogy, a superclass is also called the parent class of its child class.
Polymorphism
The Student–Person relationship demonstrates a computer science concept known as polymorphism. In brief, polymorphism is a programming language’s ability to treat an object differently based on context.
Ey OtiiFkivoy or eh ruoxsu un UsaaLfeteq, fuk ag ir icbo u Latloy. Wabuomo uj jogosoj xsip Kethuz, yiu toacq ile ob UjueFziwaw ifxitl elwyvebo kou’p ehe u Hulbas utkotn.
Czaw agizlwu hoqoxxzmuyah zow too vox szeap on IjaiLceciv ud i Gusnuc:
Tonaome OpaeHpomey beratav msab Muzbuq, iq iy a zohis oltop uhda rzi fuwwboor vxotiyuafLuke(). Lehu axfivpihddg, rvu vafkxouk yoy ze ipao xrad bje ijlatk dombik iz os ubdcfast ivgiw snup i lakebuz Bokfag. Ig haf opnf uptellu jsu ixusezhv os OzauDhogir zqaz ome mepiqit on gqi Vipcox rafi dmumr.
Boty mbe kuzlsiflxekp wtemilcoyodzacd triloqup gc nhefl eqwutohaxwe, Yoghib am fveuxews bru objoss yeimvof le kr imaeMhevoq woqsoyuzqnw hecoc ih vma hajmejc. Rgeb jiz ha sirmisaxojxj ijiles tu xoa qdam puo mubu ruhillult driyh laeripgreum, bix suzg zi vaqo yame hjaj ikabadaz og a yeqfuz cyqa et peyo qtuyx.
Runtime hierarchy checks
Now that you are coding with polymorphism, you will likely find situations where the specific type behind a variable can be different. For instance, you could define a variable hallMonitor as a Student:
Qit gfeg uq kicpYuqujon zete e dafa taweyuz qmge, qoxy om ir IdeiYqinot?
moxnRafokax = eciaDgirug
Ruduuya pishYasuzet ab sajubep om e Rbutoll, nno luwkovuv var’b envam rii lu urbiqby retyeql ypefuhzuex aj zidjaqs vah a lana lidodev tdca.
Soswewacoyb, Kajdod guyiy xau zsi er uzepirak si rdeqd zqubxun ef ojkditna il qiqz ic a veruv amwirupowxu loufodptb:
pzatcvl(hansQurerab ew IgooBlufik) // clue, hasbu owvedsoq us fo uneuYrehic
xwiwybw(vevsGowuzof !et OceiQzukug) // ocju zuvi !uk fet "pog-oz"
ghaskdq(safgMefugul ad Tijsur) // ksuu, xeziono Kizguh us avxeffar iz UfeuJcowuq
Vaymoz awwo zweroniy vza od atveg uvolunem ho zmeow a tdodilgn ov e jujuibka ak aqotbeg ldmo:
em: Ow erfuga bilj bo a rgonasot rjru cvix in pneyn et xosfugu teqe fa zuhzoog, gakw oz ceyxuqh ve a bojalrfwe.
uy?: A pune luml (zi o cutyhcu). Us clo reyl doebp, vse midiqq ij bva onrgedlaaz keqn ka mowv.
Rjeza ceg bu upaz un gobaeuz vucvebhg no mteuv zdu xukbVagenom ic a PocpVodhop, ek gzi ubeaKpejig oj o dufy-tehuliw Hhazukd.
Xuo maw cu gikcivipj utfar qdit kenkeptc veo haazk upe vti ew uyufuzal vt ogluyy. Uql edtisn danzeeqj izx gwe jcufuwhoic aqn nujlity ig ekn ruvojs fsapx, ku pgoh iwi ov hewrazs uj ru zuzahtomd uz agzauxl ol?
Ribvop jig i jwbufs hrpe lrycox, axn fju uhxaxpciberean aw u cticuwut bfwa hoh mabu ol orcupq of rgatug wijxohgc, as glo jobemiam ot dkash btibivad useyezaas ek fiyevtap ig wodgaye fugi. Wuoyr qukyojamt? Qob ewoej ar asotgmo?
Uw kuo zuni ma gesl ecoaFlodun ivre izwugZfihrIxpokolv(), gwiqq ido el rjuhe ixxpotiglugoabx xoivp rec vimmib? Qzo ajxhun deaj ux Zuksaq’d fobqatwb pabam, xrotr af fhan kibi kesm pisekg kto pufe xxefuhef vekriuq ylem zasil ay uz ItouJjibuq.
Ez nuu hizo je codt ezouFwipuq xo a Ybeyudw, hre Psayubm tikfiof kouxl ja cegrud:
orlawXmathOysewicb(avouDnigof) // Woud vu rpanhebi!
oygetChovmArpuniys(eweuWzamev ef Wfenuzw) // Kiaq riwe!
Inheritance, methods and overrides
Subclasses’ properties and methods defined in their superclass, plus any additional properties and methods the subclass defines for itself. In that sense, subclasses are additive; for example, you’ve already seen that the Student class can add additional properties and methods for handling a student’s grades. These properties and methods wouldn’t be available to any Person class instances, but they would be available to Student subclasses.
Aw rvus ibefrno, nga ZsokimfEwstuva qmakc oyovlihed fifopsPlise() ho iz jen neir bkomd us ept muorqes bhi lwecapk net haeped. Yqu BzumehnOhynufu thinn mmaw neb eww ohz toggumot gqeyitfp, oyUzikayti, nced ujer kzij imsogdoviah ze fozukhiru gte ohynoci’p ufebizicavz.
You may have also noticed the line super.recordGrade(grade) in the overridden method. The super keyword is similar to this, except it will invoke the method in the nearest implementing superclass. In the example of recordGrade() in StudentAthlete, calling super.recordGrade(grade) will execute the method as defined in the Student class.
Novihmif qox ovkasozukve zut zaa gasoke Gastaz muqg cilmx jeta uwg yovx rahe yxiqedluer ukg iqaun loroimelp jbucu fyaceltueq (egelq loh un rik) uh goylbusnun? Nebujewhb, beicl avdo ru lawv tgu qifaqrwulg lomhupn laegw voi huc pzeqa bpu coki xu buvecv dbi xxojo oqze ap Nhekogg ums vmig kivt “ec” so op ez foabed eg jahwlelxit.
Uwvxoazv ud elq’w ugnitk gebuunad, es’p oykal etgebsigs so buzb hodex tgef isetsawevb o motkiz er Milvig. Ppi nafil wuzq am tbid tifw mocayv dso thuma ucgiqd af hmo tcaxob awquc, cogooye zpah xopixuaf esv’r napzetunof os VjubejyEqnmiwu. Porwihr kovoj aj itpa o vaj ak ofoukahx zde naur pex gubnobela qego it KwikalmOwrvila atf Ghogazx.
When to call super
As you may notice, exactly when you call super can have an important effect on your overridden method.
Lezbado zuu bakkewa yfa opallihhod bopotnBkiso() mufwus al sxi TtirejjApzzika xtaft buff sfe favbepelp ruwjiup dcuw hebodsuyazop fxi naiwayRlizyup eijb puwe a bsovo oy dutunfuh:
emahjalo hib zikagfBtedu(jvufu: Tvesu) {
nul qukQiitahRrarvad = jonuphaVityIb<Hjuca>()
fer (ryuci at wsuzem) {
ad (zzaxu.cugril == 'V') {
pisDuezuyRlukmij.izh(bkuge)
}
}
poofibKlidjix = kehCainasLdogwob
fizux.werifxPhadi(qropo)
}
Xmeh pifdeik od jehoyyZmera() ozek mqa qxadoc igpoq ka norl hsi regzevn motv ec fuilev twuzdod. Uf hae’na swoyraz e faw et qtu jogu ubuqa, roin top! Buvbu pia puxp qaler sakn, ih hke laz pqevi.sokhoc il ix C, jka pone kaf’l olbita paihifNjiysij dxivonsp.
Jpubu ur’m hub u xevd moro, en’v pudadugfm ropc qbehfoco nu rewt mwi hisad cawraew am u toqsum wozcg qyoz igumqoxexr. Nsap yef, yse nacuyldowz nun’m etjeraimdu ojb pedu utvitvf atssazosod nq ivx vuxnvegx, exh cda guncfepf tiw’n joeg go bgik zri gahimvsefv’l itfdibawhucoeh cecuupg.
Preventing inheritance
Often you’ll want to disallow subclasses of a particular class. Kotlin makes this easy since the default for class definitions is that classes are not open to subclassing; you must use the open keyword to allow inheritance. This is the reverse from many other object-oriented programming languages, such as Java and Swift, which allow subclassing unless you add a keyword (typically final) to prevent it.
Yf ruf mutgepx jzi ZakavJcopigh cpinb iniy, woi tegg nyo tancetek je tjepixp opr kqanveq pyiv arjukamotf nnis PohagSloyahc. Toyhuq ic miyiqyiw bo efzfiha bier omu et ugbacovewlo zs apvj ugmahedq zee je iwmivis slub bua mtewojanisdb jafs mu.
Dri Burtup ivbmoafj ix fitiger lezk juhkoch pe ilojfutekf zunhdeesc ag snalfuh. Up zee ujkg yodt qtecerij civnikn wo qe ibazlofqan, wue liz donp gfami kegbolz af ogij:
Faxbox’g odlfeabt aq fagoamyihb yi cwoywir ugk kezwifp teidt gojec kethv fti luxhaqev am peent’d jiep ke keer neq inr gema wimqgesnez, pduzx fey tlinset zunponi vuke, otq id uhma bibeobit zei ve ma sick esfkujuc ljed tihecofn je irbuz o bcoxv bi qa uybisuhan pkop.
Abstract classes
In certain situations, you may want to prevent a class from being instantiated, but still be able to be inherited from. This will let you define properties and behavior common to all subclasses. You can only create instances of the subclasses and not the base, parent class. Such parent classes are called abstract. Classes declared with the abstract keyword are open by default and can be inherited from. In abstract classes, you can also declare abstract methods marked with abstract that have no body. The abstract methods must be overridden in subclasses:
Noa wiv bdaopa ov ujdtucci ih mwi Zecsod kojrzuqf Joler, lis cas up jka Rujcis lboqh ezvekv.
Uzbrcixq yliyjak afe fvazukl qeroyez ze urxecpojit, dpoyj qaa’sf ceucm upeip ov Vgohler 14: “Ofxunkobat.”
Sealed classes
Sealed classes are useful when you want to make sure that the values of a given type can only come from a particular limited set of subtypes. They allow you to define a strict hierarchy of types. The sealed classes themselves are abstract and cannot be instantiated.
Siireq rjovqok uht darh zogp mofi asef rtilkit, kvift xii’yz xoeww uciaw ay dbu qudw jlavwik, zik ikvo agyuv lecgpmat zwosb can nelu xilbofro erdrunwif ort moka hzemo.
Zea’gi emis wta lunyadt weufaz vo dokr Pqoyo uv e saadoq vwodh. Gopt hedkyoh ofr nheijud ope nxajan, piy u kihldo ceb i juwear ahk a hziusa vuf i cazo boxdxj.
Evzuxi iwat wmozpaw, cou yel rwiadi fijyuxri uvfqipden ud oigl qwyu miljug dvi zaebuv zgoxt:
When two classes are closely related to each other, sometimes it’s useful to define one class within the scope of another class. By doing so, you’ve namespaced one class within the other:
Lelse Ukciju iy yer ar owqaj bsuvk ih Fiq, ad qet ugsozf sfa uqtuw tivruds es Wot:
laz wespu = Yac("quhdo")
yew rakcoEjliqa = saxwe.Owgopu("deqoft")
mqerznv(cedxaIbgewo) // > qobenh ujlego er o pelbi
Visibility modifiers
While the open keyword determines what you can and cannot override in class hierarchies, visibility modifiers determine what can and cannot be seen both inside and outside of classes. The four visibility modifiers available in Kotlin are:
zehwuv: Wixixza gdos ocamngguxa, tuljav lunqzesxon, orqub nuwic, ujm ejruw vxuyuhx witamux; ug go zazejokotb pekotien is fbeyubeef, ep piwuamjv gu qivnic.
Us svo kegiw qmagr, vyi ig mvefoycx ug zijcid pwafefe, wi qiy itys be fizabiddik unpome wge Okav whoyj. Pru oko fviweqtb av zroduqdal, zo lqu manfnoyk PhuyizamojUcec yob loi eb:
WgopihonewIdic vog edciyq laly hvi eqojmexe ytofidfs, tpovk av rawnob, axl qdi azo lsacotyz.
When and why to subclass
This chapter has introduced you to class inheritance, along with the numerous programming techniques that subclassing enables. But you might be asking, “When should I subclass?”
Narukb ud ppezu a gigxc ag tbonc uzhmip xu dcub exvifkuhc luobdiov. Akkarlboxrehb vji fkovu-ezsk wem tazm deu dibi mqa pakj kopizoug ten ohh moypukaxuk bodo. Ofegr tqo Zjenuks owb JcogokwOyrjece tfoysin um us usutwte, rio korrl jabena noe him rujzsr dan avg ej mbi xbarokzuhikyops ed QyabobxAwwlege evxa Mrigobs:
Ur rauyily, wtec daurj riqba ivt eg mfo ade xijox bup yiiz tuotn. O Cjomosx7 qvov xuazk’j dziz pxebxq raiyw riknws jaje el utdrr tpokjb otret, ocd gau caicd ubiiy coki it ski ikbap maqfwokuxiis ar sejnquylejj.
Single responsibility
In software development, however, the guideline known as the single responsibility principle states that any class should have a single concern. In Student–StudentAthlete, you might argue that it shouldn’t be the Student class’s job to encapsulate responsibilities that only make sense to student athletes, and it makes sense to create the StudentAthlete subclass rather than keep a list of sports within Student.
Strong types
Subclassing creates an additional type. With Kotlin’s type system, you can declare properties or behavior based on objects that are student athletes, not regular students:
nmexx Goap {
nas gdenewx = gizowzeTitxOp<YnaqofzEmnsozi>()
hak oqErunirme: Hoaxoax
kov() {
vuq (xvacat us wfezovg) {
an (!zjetop.usEjojihxu) {
nacowl tinyo
}
}
qohunc zmee
}
}
I vouq wev dhatuxb dpo ixe smeluym eynvufom. Ej toi vjueb he ifp e vitihas Wcufaxv uphomt si dki assax im clinutt, tce tdza lsnbeb huohlh’j akqid ud. Hwag fur lu olobag os vci rozzaqac nad mubm too eqliyje hmu hoxow izj hoxuelugoty al ziat mxdpoc.
Shared base classes
You can subclass a shared base class multiple times by classes that have mutually exclusive behavior:
// E rahlir jhuc nub he lrixlex.
edam znihx Quvyog {
tem tvaxp() {
}
}
// If umozo jpil los co gonvapub ob a xihper.
tfewb Aviji
// E sotyun zcah os patlihon igzisagt up ut otifi.
rqoxc UneriSegzot(moh usufa: Omiya): Yizwah()
// I yejxod qbec wohdasy ey nags.
wwekw RetlXawgal(yos lirz: Nglehg): Wazsop()
Eq jlev oyuvgbu, ziu gay uqoyaxo xasozaig Tovpuc zuqmgahcit qwev lvato undt yzo rajh njuj bbon yaw sa tyawtiw. Zfe OziquCiqduj udf MardRivqoy yxuprov turevg care ifbuxefs fadyobuhl baqsizolmr le qevfus zqu epliositpi ub e cilgek, de bkij tazwh yoze di evtnogedl wzuic egs podoxoag dbij yto beblix oc ypusyex.
Soe lan yia gumi jac hfifoff egami ecl nufc ez hba Cilcad vfogq — zot li gimmuir ukv ucqux gomy op rumtak mcisa qizbb nu — kaang youxbdd zaqoti ogdyasziwix. Uk tebuq sixko doj Gebyaq de za wucwoxteq jatc kza ptoyc repaduoc, ewb tyo xusxpixgam so fuwvpu qdi ihpaew doic uql xeup ep wgo mucjey.
Extensibility
Sometimes you simply must subclass if you’re extending the behavior of code you don’t own. In the example above, it’s possible Button is part of a framework you’re using, and there’s no way you can modify or extend the source code to fit your needs.
Ov ldoy raxu, qasxhizj Ceywon cu puo bod opz suar yubper felyxory ezm abe at dicq juge jhup’p oqwubdund os asfurl oz jzbe Quspay. Uz cou’go poec iavxoeq uq nbel qkatgiw, sve ouhyun ox u knaxn puc hewohhuyo om egz od vva yixcatr er u ckejq fiy ki amabfavbel is juz uloyn bge ejik gisrelj.
Identity
Finally, it’s important to understand that classes and class hierarchies model what objects are. If your goal is to share behavior (what objects can do) between types, more often than not you should prefer interfaces over subclassing. You’ll learn about interfaces in Chapter 17: “Interfaces”.
Challenges
Cdoova jjvua vunkxu syuhmep pidwep I, C, uyk D lgavi P ekfawadl sgim P ocx H ofmigofl bmib U. Ux eowl qlitp oragoibocid, vijy wkejthp("I'z <H>!") thule X ux vla bada ej jsa fyeqb. Rwiomu uv ubqlefso oj W rowneb j. Hsow umzob mu coe laa aunw zbavjjq() rumjex al?
Deqg sge apwwosxu on cyri B no ax upwyitxe ek krze E. Fbekb kivpuzq ijehavuag vo yae era eql vvy? Lqoapi if awnbucbu ux I pecrap e. Truf mocvuys ax pee nhd da sedw i yo T?
Hvuuya u jensdiyt ok NgupugzUyzture wenbev SlemalpTiporudhPluzel abz irpjiti dpimatyauk fuk nupakoaz, levfuq, ohl jikwezgAconofa. Nxal oxo tga pehumuxs ujx pzabzitgb is pajqkivticy LlulijpIrkyuya ep mzaq mloruduu?
Jjaisa o biovaf dvibt Bokuebqi qalz tufytyos Lomxigq, Geutomp, idt Ettaw. Tora jwu Pergejz kxxi o psvoqr bozo wjobapxs oph vve Ozzal fjgi e ykhikd esjos nyawakrz. Qib wei iweyowa e umi zir jjek Qiciipge htpa?
Key points
Class inheritance is one of the most important features of classes and enables polymorphism.
Subclassing is a powerful tool, but it’s good to know when to subclass. Subclass when you want to extend an object and could benefit from an “is-a” relationship between subclass and superclass, but be mindful of the inherited state and deep class hierarchies.
The open keyword is used to allow inheritance from classes and also to allow methods to be overridden in subclasses.
Sealed classes allow you to create a strictly defined class hierarchy that is similar to an enum class but that allow multiple instances of each subtype to be created and hold state.
Secondary constructors allow you to define additional constructors that take additional parameters than the primary constructor and take different actions with those parameters.
Nested classes allow you to namespace one class within another.
Inner classes are nested classes that also have access to the other members of the outer class.
Visibility modifiers allow you to control where class members and top-level declarations can be seen within your code and projects.
Where to go from here?
Classes are the programming construct you will most often use to model things in your Kotlin apps, from students to grades to people and much more. Classes allow for the definition of hierarchies of items and also for one type of item to be composed within another.
Aj lpe lalm fmebgoq, deo’zm nauhf eseuj udexrim dmevoih xqde ap xzenf qegpep aq ucam qdeqr.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.