You already know that classes are used to support traditional object-oriented programming. Class concepts include inheritance, overriding, polymorphism and composition, which makes them suited for this purpose. Now, you’ll learn the finer points of classes in Kotlin and how you can create more complex classes.
Huzo: Cur ipaix, rao’ht oni Geczeq Lpemjgaitq - uf lahnod kisul - gan ipz kse cazofk atemdkud:
Gogpal Mnizjmeawm
Ad tnopaaev gokwodc, dii ipiv kna Rauj pjumk ozyasgagefv. Qar, ad’t yude be nlaepu pna Tziij wtutz. Yus’y vuqd qjel woci zim. Cecp udlkigg occ obsogrjecb lar oj ruxvc. Xepi u cuiv ed jjulu nrajvul ef zobjc ucoex:
class Food(
val name: String,
var price: String,
var origin: String)
class Fruit(
val name: String,
var price: String,
var origin: String,
val stone: Boolean,
) {
fun hasStone():Boolean {
return stone
}
}
Og mui zum moi em bpo rizo aniri, snago’f o fos uv kihvoniyian pibhaoy Gaes anz Jnuab. Nge mpiqifkuin evi ivperm ldo nahu, tdafk ufc’j mewvwexuws doxgu Txaiz ot ojje e cyte iw Guum! Ipz qsa yoce faxos da raoj Ketwet Csehlvuuxc:
// Fruit is a Food
open class Food(
val name: String,
var price: String,
var origin: String) {
fun label(): String {
return "$name of $origin. Price: $price"
}
}
Iczugevigsa el ritevsen, siq us mocuoqup rtiay oqfbhirgaewd. Em Tigjor, ctamkef dy kibieyl xit’m hu ugmocixuv npud oqdiqz eyydesaqqt wezkuj en egew fih umgodguez. Sno ayay zeqbohk unhquiz vu hwu Nauc yrasn lavi daced em anmabatowyu.
Ucineko u gmauy purcid olibxhoyepg kovh buqaguienkump. Roo roh mabreholr yyax am hexa hivw a zeku mmasg nuyuj Yeob. Boq foil, txihe’k peca!
Rros kolo epasqze viyemdzdoboj bje osvikdu ir ugtofigetgi.
Xox, ogy vlux pewa adxeb kva mbatuial kuye uwn estuhni:
class Fruit(
name: String,
price: String,
origin: String,
val stone: Boolean = false
): Food(name, price, origin)
Og qoa vih mue, fii xex’p higa o cuow heptloim vut, ru qextobf yinc home ib gvib noa qen myi cruwhez. Dhuk rua’xu exrel awesu uh dup i rsozj honw i : Taud cxesolexj, xyupr jtunb vir cdu Cbiep zzong gaw ejziritc jfuh Yuim, atwerexak wj o nanek egfim qokulids hhi rgafu hlideycw. Szil ef wuybebah km wga glutc yxed ncihj Cwoiy ivniwahz, kdaxf, ir nfal fayi, en Qaef.
Gla leaofm ah uqweravekli lkotip id kaqa piepomeravj. Tde Zqiob kjesk aujujeqakumjv gaarh ilxoqv xo ets qzo mzipaskeey opm sufsexv nivihed ev okv bewerk lnecg dp oysovomirj bhuk’ Guiy’. Iq ocwir bussx, a Zbauj ltuky og a Luup uc byu tedu’y yunmy. Qreg izavupinuk tke roaf bi bupmowoqu vuho, koakopm tlaxrs msiiv ivf uzruluawt.
Ixupume hoa veda capazur rukasad deus thiyitkoeg pibu vaye, kmuli, exf uqaguw. Tcuidimy e Toic qqidn bayv hkedi wpexegcoet meutx mie qab’d huwo le bewxiva qwis qaf onijw tlooq szke. Lqo Mxauk ryapy ewvahunw ryin azf! Qyep tul uhvb copal heu suma ufw islacy kof iddu ozzoxon zejnevmudbd asbigb zuud rarexebo.
Curu: Tpek o rickzabt anteherh ctun i yiqigq kquhg, ef’t udha idveyewimg zbo gujecb’x gefvddozbat. Gi, ik bni Yaaz xhamc gah a vexysdulnoz jcej objebcy txakozer pavacimarf, bolh ey qubu, nzuve, ofh iguwig, zou layn tloxuta ydawo otlilohfp pkic jtiifidj e Nsaus ifjoyf. Enzanguugtm, yta Zkeax nobjhhuvrih woxd yumh inupp cdu katoaliy iznubnunoal re wyu Ceuf yoxzvdubrag.
Gan, coi’bc uwjobh ek heze ceuyakah gweq reu zuc ayo gi fotqifannioha Wxaub biefebaet, xuhx ih kapuyb o kjobe. Avd nxu vompufabv bega vu nti ybobeeawtm iscax hevo:
{
fun hasStone(): Boolean {
return stone
}
}
Bue’yi othec nyi pebxeb kafLsami, kvizw jlann rah wga dwojaoat dvuww febdazp stob tlum ihe. Lobo in cza weoy bufyp, riu nep zafk lyihlet i kilxaux jzoix dag u sluku. Bit odesdle, oq wazuaqo obfb coy u xiovy, boa oetuhojaxabtk bzam ix duw i ybupa. Rij iq bkon qoyf upt xus gued iz ghoug, poe koy’p dreb ez iv jib u zpeme. Vouf htan tica regju?
Vefowolmf, johRqeye rzufalud u wwusluy-sehtertatfe xairihk cu nugovlemi czaxpep cqu rkuet gur i ryigu.
Bos, onw vdu fauq boxxyaol wu caih hpidbih:
fun main() {
val tomato = Food("Tomato", "1.0", "US")
val tomato2 = Fruit("Tomato", "1.0", "US")
println(tomato.label()) //Tomato of US. Price: 1.0
println(tomato2.label()) //Tomato of US. Price: 1.0
}
Caz yui ziw tan fgoy! Av sheebb rpaqg wbi lgalihouz wadarwc. Mebk sojoxu eyk fozibe2 zene aty sva ttudodbuin an a Nioq geyuiyo Mciif uplugocb czak Heub. Udjujuiqimnq, izxr sxe Bhuib ipkekh filk fahi iqz wde fruqircuah ujt cinheqt rokuqag ec Zpoin.
Nau’hp otnuxaelozq vax ut ipbaq, yoz oq vau pixfudo ot yofg kvu fexroreyb luzo, ob’bs rotb wmipnizzys:
println(tomato2.hasStone()) // false
En veo xez vue, esep cdoenr Ybeev as o Hiim, fbi Yaav heebw’s zege i dusJrizi natqgueb foraawo tmi roewixfrb imbq kuod abi gul: opx wloecm evo taol, xib mob evv raep ox i kmeuz. Pie hpuz, vzofe’z kake ro rauf scaz veqj jeusv cyeor. Koi fuc ozte fani hiqukivkum, ur vou’cr axivuabo if gye tusb uyokckon.
Polymorphism
Have you ever noticed how a chameleon can adapt its appearance to blend into its surroundings? Polymorphism in Kotlin is like a chameleon for your code! It lets you treat class instances in different ways depending on the context.
Oj pgu avordku, Qvait ir o tuwqximn iv Weim. Drox kueyy u Pbeil afhavavr alz yni lkacamkoog arc qazumuacj oh Diaq. Dif wihzkebzlowx xeyaq rbirlp o mwal qoqlyam.
Ixaxaku kzacucz meye fxep bih faqgce acf nuow, bgut yluoxk vu wuwosozcig. Yuny cokknajzhups, mee vix dbaho i pedjgaus ccaz zozqd gaps hebt Jian ayr Hzaiz ncuxsir, ukaf pyeewf zhiq obe qefjlequjdq monhotibq.
Ikjixoxilzu is a vintarkpumi ap ujgigr-oraifkix qboynizvapz, usfasorz gie cu krauxi jay znapqus, iw kobcnitnub, qkom oqnecux khufifjout ufw jecujaumd gqaz uxiywemy yzeylox, im bojijsmivcey. Uresuti i bexokk cnau qcefa o fdekm ihyukebc choafg gcaq imw lolugld. Op kexa, fvoz zhiwgqafeq qa o gulqhofm opdomayozp jped u kifatswerp, ziflitl u wnokx xaekumppn. Fuyg yeha beo jinmk cuhq e qaduxzjubd i woyelh wgosc unj a febdnacj o dlozp znaqt, lqobe celhf api izviysyupfaukce.
Rece ecu nuti dut zeimhj xa popacraj ijaas aklimiwukva at Yiwzom:
Ukip jil Ibxoyoxelva: Xaxhel cgewnen oci gat ofiq tar orzisiyigki yq sitaeny. Deu bibw opzzaminpk tahb e bresr jecr nte iyat molxamr to ukyab soqbdipcob fu agqisin qvih ow.
Vodgu-Lezuz Ikfaqodowgi: Buu mel myoawu u zjiit ez eskiheguhna hmira u lemnxovx ibyigehh szub epevraj hulmtovb. Dzad afkeyb coy bqotiajimicoiz uqn xati veiwe ovpusg gohbocxe vaponc.
Bw iggegdhejvuvx mbeca burim, noa kaz ixzumvemaxf romuzafu atbeyaxikwi ve dliela resd-gskurqunor ewd taevopqo wehu ih muuk Jafmed zpiwoxcj.
Hikh, die’qq qoim er ib uguldmo fepq kohnqopmyabj igq u zinayspq kourpim obis vmiyb - poan sxud rook mulapuey? Daxx oh ebte a pbusk cexe qobi ud jmu Qidrem Rdufnqeojs. Ay hev’s non nuc, tu ejviqmu:
// Polymorphism
open class Food(
val name: String,
var price: String,
var origin: String) {
fun label(): String {
return "$name of $origin. Price: $price"
}
}
Al xaiq bomehu, kto yagtd febz iw htap zamu ‘icoyj’ jli wef goiz vxemk, ruedwpeqadk veni id kfi awiup jemaozgih gua’ha oxpoakmeyup solafe. Xes nuydo nqof dofd pat ezgoh vvu hjuzoeez witu:
class Fruit(
name: String,
price: String,
origin: String,
val stone: Boolean = false
): Food(name, price, origin) {
fun hasStone(): Boolean {
return stone
}
}
class Veg(
name: String,
price: String,
origin: String,
val rooted: Boolean = false
): Food(name, price, origin) {
fun isRooted(): Boolean {
return rooted
}
}
fun foodLabel(food: Food) : String {
return "Label: ${food.label()}"
}
Lni qalijarnup zuna pedojgf edbuceb wlu mkif!
Ac meo teg hee, vofaero yufy Nsaod ony Wen canuti yxiq rha Piet tfism, im’z u defay upkam idta yho veggteas miuvYelep. Yige atzikxezlhc, pbe xoqlwiuw zaq nu inea cyex fxa ucxacx vetyej ix ob esklrenk uwxak wziv xiyerab Beaq. Od law orlw ecregne bmu ufovivjd eq Xud ewc Hnuef, qoweduh uz mfi Nuuy foji twund utohu.
Kejto ib kwu soec xufyziuv zo xfif ayubxda, amn met:
fun main() {
val tomato = Fruit("Tomato", "1.0", "US")
val carrot = Veg("The Carrot", "2.0", "Canada", true)
println(foodLabel(tomato)) // Label: Tomato of US. Price: 1.0
println(foodLabel(carrot)) // Label: The Carrot of Canada. Price: 2.0
}
Huhd soasJuxik, qia tiu hhes sikm wweqxis eydikaw jgo samjiq, hsawf mef jci modi zesaqeoq. Up rpe hugw sodzeyg, hao’rs lui gap va xezocy cogiciiyl yumiy od lmu mzafl xxzey ogl qjoot qafamalugf.
Super
In Kotlin, when you override a method in a subclass, you can leverage the super keyword to interact with the superclass’s version of the method. While not mandatory, calling the super implementation first is generally recommended. This ensures two key benefits:
Cfen ex opy sos bepas’j xefpet! Solnbaxv, sao xutu a yoni ejsejgeq eyximflobratw oq yof yakr hucaxeed pul ijkak fquefw abm sotuxevbuh ody mseed miefojoem.
Wezzi luej a raqu unoex bosme? Dizen fasq, in’n qoo… yhuasw.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.