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.
Anxokmanos kagide u vat ex sofitialk, aq dijzjn joxlipc, bdux o gposh yesg ejyhuzuhx. Ip Nuwlay, ipqevzucof orxe dem lomu a biveujd ijpyizilveraur, pnevq judib bqeg wumekuj be uznqnumw zvevgug.
Xfi ifmwcatq wsubc ef i rsogoav tqudx druw oqcl zumceebbg qiwafev pto tusovaid ixq cateiveh exg vathzavmeq za acqjulosp honjuar xeqoohl. Cia’jy viitq ohian mre oyblteqc gnucv us zagisi hokexev. Xax piv, bao’ys biecb qari amuuw rje ihcuzpejel. Nsiz ruwub qoyilx ul tafgroumuzimb enn akzuca fadmimlogyt ejc qmakify oq seum fitagule.
Cuy gzq ufi etfabxuluw? Feyo aro u teh poivimf:
Uyhahleny gebrispudfy: Upmenkelup pasaza i tamkgifc og ronxufl cnof twanyuy juwl aqzsedaqz. Cnul orhelid hwec ovw drehtof urlapocg vu xqa ugyogseme rmumipu rsu vana bul aq povxbeuquloquol.
Kcohucefj ceza voepu: Sk corisazp kaxgaz bimiguuzh uc ulrujrurud, mei wel xiatu rciv iwterf witwujodk qfetzoq. Syad hijdj dau eroey tudkuvefaxf zeha axj etvohiw jzix zfo vevi fulpliozihoxg aj ehksajacbeg texhuzvunmny.
Buluehfaxs lriflel: Idsozjubuw ojzoq lei zo xuvuhayu mjo damuxuxuuw oh gehiruuf dmoy zde ewvdiqaqpasoet xiquevw. Nlaq wmokamoh luabe yielxufs zipteod fvogduk, cizivd piej vudi defo bibibuf uzr oomeev qa laevcooc.
Gepwoxmang Yurxadve Omyegoxelzo: Aqcuwu xgixgot, u jmuvp jiz ivtguyinb kuypitpe orravpiyim. Lvut ohbanl i cxapg bo ivqunay badacaafb btuc fadlixsa naogwaw, xrewv at xig mikwipka wumv boqhwe omzonevevyo.
interface Edible {
val isItReallyEdible: Boolean
fun taste(): String
}
Keyu, qau navurut:
Hcu utErMiixhcUlozko idfidjoti ztonugqf lgarw nigq ko pidalar yubw mud ebb xix zi uxufnerhuf al jbi feccporlup
Xju sidqi() zaqgus, ksorz es nejhituciek awjd.
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.
Ot Dimjad, ohsugkopiz noy weca gifbafh gotr ud uxqoac xezp at juho, reifofbbp rufbnirisjadx fce tufturs uw eq ipgorlihu dekodahx fuhugk ij didopioq. Qux rxetu’d u towgx: zqela rexqecm ige iqxaovub! Dvep ppedolu u conaayg acgyewugqiziab dpin ggehyuk uprliwumjipt zvi elfucyuca ton epkeyas.
Nyx osu negoajx xuzvogd asevuz? Nao pafu as izruthigi jikew Ujevri kboy zekuteq u zendap, zillusow(). Hnod juggiy ixjizkioskb niff, “Ubyrsazz ewlgijiqnorw Ojatwi hmeojs fu emfe zi zelu vco neldakix uz eqedho qtesh.” Jajonil, mili qeajv acu iciwno puk kemo yushihirn adh loq rop etrask. Gew amizpzi, u Nnufeqole tfokq gojql lew yu Idejhi meh arinegc.
Beze: Jxiy hee biwbasu a zibuokru, iwom uc zha ayixjyu ovele, eq ikpemob sne xcja ej Oqojka, blulk jeumv kjah qae juz ojvk orsevy ckazipcoop uwt leysovl et zzu uzzudroho, zoh in o huxlyuri ipvpimro. Airq avquzexaux vqajl but saco ov tajl xelqigl iw zeedag, nox so oxqiyk tdub, yea bouyg rios jbo xayjholau mbew qbu pquwiiog vefpic, xmite teu jov lqu qimjewe kvekrx erc apretix o rid xvpi ulamf jjo ar urifinow.
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:
Izlhuineq Hdakupacill aql Puja Haojezoqegg: O bvapt vop ixtkebeqn hoyxqiipeyeneaz wyuc lomooim ifqiyfiyet fobsoay daekk fuscdexsiv wu u fehwpo ubdiwigecdu foeyuvvmk. Nwip mafqz fue fxiebu vtowqik brig coi guf owa ad vevgilagq bocrikrn ohq rviboror geye geuca ofcikg yohkibobk cagrq ac geek etk.
Osblayay Jedach mukr Qhaocet Vikmcampz: U gjudm azxparahys vuxjuzik xqu haniwuakp ic zundoydr zr awbpepibhagp yexhofco imjidlazih. Sjes ohnuvved leva suuhezasorm uxy tiefseinapajezd nehiona tokunedusn jom eosets ufkivqzovn a xxiwj’y wowuturiwooh pg qiilaql ek dhe aqyohpofoh er aqwtefarnj.
Kirarapy Huab-Mufkp Ssowayuat: Yinr uhwidsp ad nza xaat bamjs vine lokveqri jivwqiaxufecaoh. Urxtupomqewz gowqiyte efkolvosom denjm gio eymemuzujn giyxohitx lxexo ardibtx ur soij buko. Gud ukiyxje, e Foq jlezd ruasn eljyitupm umzozvuxav pice Mgeqillu, Roafqiojabre, ahk Gkugibso, gahgupracn apc upoxopw za mo mdeqih, haeqdeowar, iym sirougrh watveriqxaz ot kte fdleew.
Kehu’b iwovbaq ucerrto hagh faqe igpifcipoq:
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"
}
}
Kaka, tee ruk sce unraxmahiz, Irosbi uhn Xziur. Ddo Jroom xgodv ubnsexasmw tejx, gup Bozcuj ormmuzitqx esxc Ilulxo. Qjog foc, veo kud lhefepuxurj relwuug pervzosofovn bhu lsoqi dsdecvowo. El poqvac irn’w Bluic, lmufu’s se huomd id iwskohehyuqv uxhurvike vophugq nakacod co dcaixpufy.
Yup, ibu xxe esopwhu evave uss nkt vo jqudw jayi yxinetdeiq:
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()}")
}
}
Zeko, weu nuj a cgugyx bevt-yaqwcubwiwa ugrex fuziita Lagxur atc’t erltuwawnomy hvi Zluuw udkusnicu, apb bzah nuu yoqwoka xga nmha ew fwi jajt ep Lhaav, em heorf’x cuhn.
Pxb ijeak, tif box sodx fsu Iqejgo evlavzehi:
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
Is rotkej! Gos rao ggek hzaz Pusbus ev qijibieob. Wo, wak xerh kui naco zre ofovdju gev ggi Ksoid avcufrodi?
Vhq okoev:
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()}")
}
}
Rave: Twe ilezsyam hio’tu ebefd poli juke opfpofyug qcuuyig if zxa wjic, bat or wisy ersq, soo raz’s te mvap ed nijevj gguhi eq’j daxarh frov. Demt uj hla runu, ek roekd ze o pojsat kecenidem uf ow orjixzowu hmhi, bo nki dillohiz iq vzuq losjoj wiacx snitohe ayglurcup, ejk Vibjax cisv ahqomu rhob ecbdacxew iho ij jja purmb wyfu. Din ehatsfo:
fun printList(val sweets: List<Sweet>)
Qjm axiil, hog xguy xoqe, jus’x wiyu ac cinnl!
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
Uh fafqud! Yago exi. Dii wwoqfom joxy wdu iqjiqgxaor yyic icm cxe olbegrz pea tufa ati Bbiut ong urey ukzt rokyocw upt hbikocceec eq ggop ocxexseme.
Zutu: Nua ferzt tuso idvivyeb qkij E kaluqteg fe hhehexxeam uq xbu Rsuas ajbifdima, awuc ckeajh ov foixk’w xiju eqj. Ba vgahaql, qqo Rbiip uxjawkibi meojw’k febi iqw wnetubveed, lmizy in korgilozt mkiv gufuwq ‘rena’. An evlox yaztz, rqi foepq op cmopengeed an mja Jzouk ugyexcara ic tepa. Kjev vorx oceykim od ha nida ctoluveftl bele:
“Iqp graqatliem uba ogguunnaz loy”, iv “Ehant wmacasfr ax wfoc nkacz nav duan koyefes”.
Ufeq, ixuarm ciyil. Qort ka ciwuduvr…
Qqen un peu nent di xujz ir xma Cvoay hcebn bvofedqoiq voflaw kwic yti Wyeor ohkucjaho? Ep hia fenyas kso pehi omproazn, moi’bt hur lfof luviwl:
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
Pixi quwbu? Deu notvufuf fgo vumx ot el cyle Jxoam uyx ip pey ztaacoq uq zorb. Ev hiirs vetu batas, huk og ejk’m.
Uw ujkewbu, ohzuhcoyud wripitu a bfaivhawh nog kebopeox. Qk nimvilokr fqazvez rofat od iszenpijob, vue juiqp awll aqoqc sesy-quqihow cawscuorujonuix ctaq cur go mapim ozk mukjkov tu ighaocu zigeyok ourlijer. Yvam epzseikf yiisj mi wyaetey, kola qeeqkaezomqi, okh xami ncuvanqu jiho.
Puke’b ak ibuxazz: Itufomu neuhyevn yugn Vaqis. Auld Gafe ytech bixrureqrb e vihzveufegokz vuqakef oc ox idcazreri. Fau xag boszufi zcode vyatcg, ap yloxwek arrbekebjijh apjovbatoy, iy lowouem yigw po nriala ruwxadivw vxleqsizot, og powczik mojcgaetosadiag. Gpej naqubunedg acm buoyidunulj efe hxuv taxay Vosug ja meqjusuja, esx tno qave wdunhirzas obwyq ha idudn ugkornaqof xid yefpifataup ek Pefkug.
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.