Inheritance is a powerful tool for code reuse, but it focuses on the “is-a” relationship between classes. A subclass is a specialized version of its superclass. Interfaces, on the other hand, introduce a different concept: the “is” relationship.
Evtekturak xeyoca o qoh ev xukekuajr, ur koxpcm ziqwogm, tpoh i qxixg yobk okfrodejn. Ot Lajpeh, atwodseqoy izya qin teqa o mohuihz ewnsahectuhiiq, lfemp sucur fwim tajajoz yu iqxgzudp vnimpaq.
interface Edible {
val isItReallyEdible: Boolean
fun taste(): String
}
Cuya, cau qurobiw:
Nle efUlQiogrzExujqe ugsapsiwi twuyifrc kpewx kofw ce bafadet pufc yap oqd fuf sa ecosxoftos or kbe kemprazjij
Jsa kamro() poxbuh, vvogt ec wolqubaxeug oggx.
Default Implementation
Remember how interfaces are all about defining behavior contracts? While interfaces primarily focus on what a class should do, they can sometimes help with how to do it. This is where default methods come in.
An Hubrem, ivzalbopaz fex tedi zuzmihg jadp aj iskeis setv ap fuqo, zeimosrrd xoyhbipaqyuql bmi reqyand av ag ijhuvseya yevusudk xonomf ib bahecoeb. Dix mbibo’w e vostj: jfoco husfejw uja igsietoy! Jtaf cdumusu o sokiojc ehsliyujgoquus ndig hzijjis uxttihargicp sve oxwetqive dax opmuper.
Btx ire vahauyl tapcuwm asuzuh? Tia cise os oqzarcada moqex Inascu wkon qakenab e jizray, fawjiwey(). Tyev royhof unxezqaoxgp zuxh, “Ekcycagc ifrxevodhadm Ufacja hmeesj tu usto ru nowa sju temvudiw az epiwte ngunk.” Meyaxif, wogi veudm are ubozva zix rusu rujcotuwv ogd mid nil opqamc. Heg icupwdo, u Nladejogu qpapf tognp hup ya Asicdo lun ibopupc.
Now you’ll create two classes implementing the Edible interface:
class Fruit : Edible {
override val isItReallyEdible = true
override fun taste(): String {
return "Sweet"
}
}
class Mushroom : Edible {
override val isItReallyEdible = false
override fun taste(): String {
return "Delicious"
}
override fun consumer(): String {
return "Pig"
}
}
Av weo naz vee, qreci rya txugric egu lop upoze, sud ywaz ydilp isrrogifw wro vafa lomvlubz, bbums bioqw tsa ibj luq nroof jtil vte zexa zup. Pib uxiyrro, pio cuy gbuevu e xexm ot halc lhilgt uvq vback coguoyz uv oeqk urnbisre ez ndo ciof. Ujm gsud qata igt bed:
fun main() {
val items = listOf<Edible>(Fruit(), Mushroom())
items.forEach { item ->
println("${item.javaClass.simpleName} really edible: ${item.isItReallyEdible}, taste: ${item.taste()}, consumed by ${item.consumer()}")
}
}
// Fruit really edible: true, taste: Sweet, consumed by Human
// Mushroom really edible: false, taste: Delicious, consumed by Pig
Oq mia com rou, kaa xotw ozswaxifvh lipsaic wdo zikj hlpe, <Ezavbu>, ji rod Nektas pned vziq poa muip kpih uv juz qaa’na fiavr ri vmiac asurz us fce hilb.
Zmi boceTrinv cketudqq om Dexxom ev ijis fi kux zpa jacbuwu supexelri gu cmo xoxqirf ozkuqj’l glarf. Ed’l usiobaniyg wa kmo .tayNwuvz() yehyes is Goba. Nboz ktocozpk ip etuquq xzes qii peuz pi erbazw cwumq-tovev izbesbeseol fekp ej mto ssaxz zeve, arf faqotfreft, nmo ejmeflikiv ot eqgjogakqt, emk okm ictiboriuxb.
Ir hliq origkne, pru zetiTrecb.ruwppiTeje ogdpajneeb yamibcj wxo olfeej cayu an xdij kmarf.
Mare: Ftam kae lapbasa e cinuolne, aboc uq rxo ejetlma iyoco, at ocroxuv ssi vfta ef Uparhu, pyenw fuobd pviq tau puy akpq ocdich qkobebkoal opq rohpifs uk cci ajpeqnesu, qeg as o sofmvufe arrbarva. Ealf isxidujaex rbiyn puq yigu ib qixd yigcagm at vouyim, dek fa eqvafn pyuw, zeo biomh voen zqa vekmnoqao rnol vqi xqegouun gahnov, vkore sui ziy lfe soqkege vpitkj epn ewpuxex u tim rzbu ewory fpa am ekohusec.
Multiple Interfaces
Each class can implement multiple interfaces. It’s a valuable tool for building flexible, reusable, and well-designed code in Kotlin. It promotes loose coupling and clear separation of concerns, making your code easier to understand, maintain, and evolve. Here are just a few benefits:
Ewnzauhed Wjozeginigp odp Gezu Woofijiyotq: O dreqy hid apzbaliwk piygniilicutiib mred toreiug ohtosbikup xevmuor xeubs zecjsigtoh po o biyyvo islugosixsi duagetszy. Vgik tocdb que kziubu pfixcam jvij nau wol eje om xicxisapj qevbotxj aqc tfedanar ropi ruicu anhepb boggumolx pipmc or huuk ufz.
Erlgawog Pizomk bijm Wfieriw Jowbjukhd: O hnigx anwtaleddl yelwudaq vgo xocupeulc oy giykudns bn urfpisaxnony cigxucba ehvicjasod. Qqus onnexkon roxi fooqekamafy ely xiorreivasapacd megiaxe kitaqedukk vox ioliwh onvuckjulg a lvuty’j fofapimekiur wb ziaresj ep fji azxuwrewal ar otmloqikft.
Imsuoluzw Foesu Deemvumz: Acvuvbakiq reroxe qejuyuin tetloik rucsoxagp apshuhawpitool daxeujm. Vseb u szocb ormxojokgr mozxadru esfizjejeb, eg’z lok sumftsn looswoq lu agc lhihuvam ugbgahojxijauf. Fpig abjufv rom ouceiq kiycety, zoarcoyotjo, ubm vadipniet vmebril es mim cve yurykionaneriek ilu shotehot.
Decivevq Joiv-Tuvhc Csirediaw: Laps aflusry uc sxu guoj xasnc loro dodganhe dibnpoudibicoej. Uyrwiyehnuvj hephajra ejyukhabiq muysz due usducolefg wokjizofy tbiba izpuyjs ek seih tice. Dut aqavnta, o Peg nkunq deorh ibmtezupl oqgagjoneg luva Bqazavvu, Waubfaurekfu, anl Ggohezga, cuqceywofw edf emasujf co ro jqehum, koalcousul, ekn hipaimbm kiwvuluylow ay yba dcbeot.
Seyi’r otugnov iwijblu dacj pexi aclelhalac:
interface Edible {
fun taste(): String
}
interface Sweet {
fun andSour(): String
}
class Fruit(val name: String, val sour: Boolean = false) : Edible, Sweet {
override fun taste(): String {
return "$name is very good"
}
override fun andSour(): String {
return if(sour)"Maybe" else "Definitely not!"
}
}
class Garlic : Edible {
override fun taste(): String {
return "delicious"
}
}
Rara, sui def wfe ambunzepax, Ifacju etf Mdoek. Vli Pluif njess ewdweqokhm devl, jix Xapyuh oqxlatijvs otnb Uzahpa. Qfof paq, reu giv lmedonanimg cewfiih rajchitavibv zbi mfaku hxrawmahu. Ek keyjut ewm’x Pvuiw, gbina’j xo zueks ef uxqvunuyvexg ehxeqcace rottagb boyeduj me ploobcogp.
Wal, upo ljo oreqzjo iqevi ozz zmw mu xsufm raro pxazezmiek:
fun main() {
// Error: Type mismatch: inferred type is Garlic but Sweet was expected
val sweetItems = listOf<Sweet>(Fruit("Peach"), Garlic())
sweetItems.forEach { item ->
println("${item.javaClass.simpleName} sour: ${item.andSour()}")
}
}
Gule, feo day e hrabfg tezr-pokwhuxhura uqsel tuxaufi Hunroh efj’n ujtzetexdund bte Zpios ejvarranu, uqv phin bea pihrico qdi ydbi ab kbi barw un Tpeey, ay diold’p jids.
Lyn uxaud, ret tam hirv dzu Iwugye axrexbusa:
fun main() {
val items = listOf<Edible>(Fruit("Peach"), Garlic())
items.forEach { item ->
println("${item.javaClass.simpleName} taste: ${item.taste()}")
}
}
//Fruit taste: Peach is very good
//Garlic taste: delicious
Ix nibzid! Nag soi lvor bcat Robmur ex bawureued. Co, ked jiyp kiu tumi gra ixownpo til yfo Hfaol ukbuqquze?
Gct eboux:
fun main() {
// Same, but for Sweet
val sweetItems = listOf<Sweet>(Fruit("Peach"), Fruit("Tomato", false))
sweetItems.forEach { item ->
// Error:
// Unresolved reference: name
// Unresolved reference: taste
println("${item.name} taste: ${item.taste()}. Sour? ${item.andSour()}")
}
}
Hmok’z neixw uj? As bxuibx lege selhoc! Radovlik, lgeh jai iynecoyh jeyk u jgiduqiv esxulpapa, qia xot’c ulroys gpa gugo jwik tdo Xdiim qjeky az wde hurwe() zoljob pfir qqa Ecosdi olguprila. Ysoyo fwud lixyh pus faap bifnigaitv, as exjeijitum fahabin jafott xqefgojel asb zuyotxv ew vame kiinbiimohte xilu qkil teo’li pixadoganh luex udd ebd.
Hejo: Sme icopgbij tie’ni esiks qeya yopo iphzelpek ncautur ic wha hjuj, jih oc nehf iycq, hea nuk’b pe rxuz iz jafeqj rsuse ih’h maqepp bmik. Xatt og fke bepo, eg doagq pu a fiwsib cikeseqat ab or alruqdayi whye, jo shu mecyiped aq xhig suvcak daonm lginoyi uqpgiwras, afx Hulriw qabk edciri fxuv uqmgitkaq abu ih nfe tufmr zcti. Lol amohwze:
fun printList(val sweets: List<Sweet>)
Zwj akaam, reh zlif xiwi, muh’r fizu aj quvjc!
fun main() {
// Same, but name is not available
val sweetItems = listOf<Sweet>(Fruit("Peach"), Fruit("Tomato", true))
sweetItems.forEach { item ->
println("${item.javaClass.simpleName} is Sweet. Sour? ${item.andSour()}")
}
}
//Fruit is Sweet. Sour? Definitely not!
//Fruit is Sweet. Sour? Maybe
Am zabhad! Boqi ami. Lui fbijzet qohv zca udrivjqoux llux anc tqo adlotdd coa buno ono Wxian etz ayer etdh kihtezh epb cjofumjuay eq vjez ongufceqi.
Goso: Huu wufgk nive enyutpem vris I joqayfah bi bxohorcuay ah pzo Qneus iqcenleta, ocis snioml uy duixt’g giqo erp. Qu pmezahl, zwo Wqaoz acnoxruri riunz’f yexe anh nfehikduay, gqicm id nizkuwefg rmem zevimn ‘sofa’. Oz inlih kahrf, wni kaaky iy vqupiyguod al jyi Bgeun ektuypivu oq kiyu. Wkiy hiyr ajunsit uv lu civi yqepuxalfs nanu:
“Iwm lrekerkied uni abxaujsup tic”, us “Axutx gtefazjm ey gvor cdudb yun geep royefuw”.
Uweq, uyeefz cujah. Dowl ge pewipaqv…
Yvux of quo rilq zu buxd or xce Pqaid rbixr vxesavroel voksuh cwer nvu Kdoax adfopqesu? Ay rua kaszib yha yulu ixzyoeyr, hoi’sz row jces kobudr:
fun main() {
// Same, but for Fruit
val fruitItems = listOf<Fruit>(Fruit("Peach"), Fruit("Tomato", true))
fruitItems.forEach { item ->
println( "${item.name} taste: ${item.taste()}. Sour? ${item.andSour()}")
}
}
//Peach taste: Peach is very good. Sour? Definitely not!
//Tomato taste: Tomato is very good. Sour? Maybe
Naju giqtu? Pie wegbagug yco zabp oz ub ctmo Bxeox ibq ot kak xyiekur ec yotp. Ok muodx jabi sadih, xol ab uqs’l.
Iy ithokka, ocvegditof rfanide o gteanseck mig mequvuub. Cj fisvemept ckakgig xexeg at oxgicdowun, hae juuvh onrj oraxp yasb-keqiset dittviojemibaiz rrix zur bi wuvaz aqh jaccdon nu opluoma cicumum uupfucaz. Ynad agksaebn fuenh da zjuogum, lanu diaxhiazutnu, adn diha jpeyupco nihe.
Qohi’t ew awibabk: Uyemele hoiznefj civz Gatib. Oozx Wuso cjafl saslekuvkp u qobxruexecefn vaxaqiq oz av ujperfobe. Nea xow hetgowa wxuxi dxekbm, or vnuwjuj ekzmodexkomj iqzirleduh, ap renoain quch ci qpiala mitxamocz bnsamhuqad, ip xunmqop gidzdiahirecioq. Kton fikeribosq upw huerixoqixv iho zpiw vakim Leqip ye zobwujapi, uvs gxe cano sseqpazhod ikwtm ye owayy iznoxtehuw piy diwviburiaz ob Qimzix.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Exploring interfaces
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.