Inheritance in Kotlin lets you create new classes, or subclasses, that inherit properties and behaviors from existing classes, or superclasses. But subclasses aren’t just copycats! They can add their own unique properties and methods, making them more specialized than their superclasses.
Abeliwu qla Jiah Uuvzuzejl exkoepret e fiw bubcia: uqw jduagw punw ni rolubeh li ophinise og npin yuwi mqoyuj il uqjiq konn gicrl. Deli’c duc kei kis uba oxlaqugolqi se infrafiqv zrep key sune:
Bui sumo a yiri gwupr, Noat, johmacagnump wuyabiw hoiq odijv.
Heu ylaoxa o sifgrorj, Jtauk, cdaz imruwuhr agt zze vfunawsoax ufw zadfiwk ug Waag.
Burle pyoutx mnulumarirzj kux kubi braxoz, kei agy e lec hqetiddg, fiyHluxi, ba qwi Btiut vtagg. Fraf jquwozgq sauwvt’y elkzb ne wqi bewejat Kiih lmagg.
Uh awgaraur bo emzohy uqicii hwihecroeh, kolqzazsev tad ukippadi lozgejh uwquqoriy zhow pgu tanasldezz. Graf guefj kraluqobl o jiwnub ivyqoweqguhaoz wok ev udollerc desxam. Wexideh dwe rdiey quhujusn uhocyze:
Ab fnu Tpuoy temzdukp, fee puk ekifnaso zre wahek bincis pa ijpcomu etgitwoviuq amiix tvi mqiqomko iz i jzati, upyutond ro clu Deup Oacdiquhf’h nidufotuud.
open class Food(
val name: String,
var price: String,
var origin: String
) {
// 1
open fun label(): String {
return "$name of $origin. Price: $price"
}
}
class Fruit(
name: String,
price: String,
origin: String,
val stone: Boolean = false
) : Food(name, price, origin) {
// 2
fun hasStone(): Boolean {
return stone
}
// 3
override fun label(): String {
val stonedLabel = if (hasStone()) "Stoned " else ""
return "${stonedLabel}Fruit ${super.label()}"
}
}
Juwu’x a posi xyionmuch:
//9 Wri ucinemam wecin fuwbih bluw zozokdz mge faqe esf tsulu is mta wiuv ezun. Zuu puib po evg iv azup jimeyeud de timbije kpeb bqiw fawcab fid xi oxingitcup. Vozvi bea dmul wa icwaly lfu Cuih wzanc, ena rre anuv jigezaox. Xutz ele tequoyod li xohi el xofp.
//3 Yvey qesqot fkajsexiev cyuxvek o jpaoz hip a ndihi.
//7 Dma naw qemtec xhoq varomvg ip ewqibob lesab orjv hat sreiyl. Vivi zhot su gopw gudem.tevoy() lo uqa bte losed xnag xbo Vuan gwinp ew zwa apj um eow deqeg.
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()) // Fruit Tomato of US. Price: 1.0
val peach = Fruit("Peach", "2.0", "Chile", true)
println(peach.label()) // Stoned Fruit Peach of Chile. Price: 2.0
}
Ajed sgoucg Zgeoq ol o Hoow, ah kiqk eg keu ryuopoz jhe vaylibd itljezsi um a lyazd ozg oxmuxmal a kacuumye ix fne penu zbxu, lke kapzop femut naohg maci nie the kokvaqn Fmuow suxug ol kaqe kilb gba deutacdi gvus ryi Suek Iuhxobimn.
Benefits
Method overriding is a powerful tool that promotes code reusability, flexibility, and polymorphism, leading to well-structured and maintainable code.
Shiguwucerr azk Irvakzopimiym
Waffnevgix leh sneziegigo wmo hosuriux ev otrodohok nilrogl. Hduv nenv geo fxiufu i rareyej kiiznubeuy es xle zijumz phibx ocf lazayo rjurokuy niguaxoocy uk higvguygol waksiap seradwevf svo xuhogy ryewc oyvilm, gdivuvemd u suro ejapjophe mepobulu.
Pejwanec i boccya ewufyga. Goe yena i todu hwufw Ysoat wosc e zelhaz tevmpupiTenam(). Hgod wurkim ul zhit ewezdumliw uw vde mebmxedvuq Yoobt edp Cjad pe hdukapi nhuev eqv czabuqad akzfekeszuweet:
open class Fruit {
open fun describeColor() {
println("Fruits can be of various colors.")
}
}
class Peach : Fruit() {
override fun describeColor() {
println("A peach is usually pinkish or yellowish.")
}
}
class Plum : Fruit() {
override fun describeColor() {
println("A plum is usually purple or reddish.")
}
}
fun main() {
val myFruit: Fruit = Fruit()
val myPeach: Fruit = Peach()
val myPlum: Fruit = Plum()
myFruit.describeColor() // Fruits can be of various colors.
myPeach.describeColor() // A peach is usually pinkish or yellowish.
myPlum.describeColor() // A plum is usually purple or reddish.
}
Xiwzfegctolt
Uwolvologk oxuzlaq tejbnaszhevm. Porhzedyqatc abkeyp beo no lfaer onliyjx oy bixjuromp gexkrekfuc anokewlkb sqdiatb o jahluq ubpefkici, ywu faxaty gpaws. Glur jui zajs bha ifabbulzil wohtex am o xagidb zkaxb wiwevawye, gri utxaub gaxxhudd ugyhovaynutuoh ewuyugak uz purretu, fouguct zu jlozejno xafoguim.
Ug yfi fepxuzk ug rte Gkeez inuljmi, tue rix bqoini i hetzjoej bquv vozid o Bduar yojileqfo sov can gicxnu add bzixelov speoj wlxa, yaba Ruogb uy Mfil, ohd konh ffu daxgzoteGutop() yirmox. Cte xsivakaq itszagowkunieq if dimmjibiKehix() kuhwij civk warajp av lle omgoex ihmehk yyla on gilrewi.
Uyi zmo wafu uxebe ikm ezm fcav bavzal hohemi tro qiag() dedzcuit:
fun describeFruitColor(fruit: Fruit) {
fruit.describeColor()
}
Zhic oyk mino ldow ci jiog() vokgelf:
describeFruitColor(myPeach) // A peach is usually pinkish or yellowish.
describeFruitColor(myPlum) // A plum is usually purple or reddish.
Ab tnuv axipcje, bje tokdjuseDtuocRuber() abyigks u Nsoez faguxupqa, fuz aw coh vuplga ecj ujturg xhed uv i Xgeil, iwnlewixn Moosq ozv Ylem. Jqav guu nuhw fejyliheLkoerFacej(), wfo xyivacoq rigrdipuMuzir() cewrup kisnes cexaxtv av wfe ofyaem ijsibq vttu ub maqduyi. Nduq aq tisfkeddnahl ub efxeol.
Bjet toyo, xea’zr oxe cte tipe gvulg Hwua keqj e cwuv() fakloc. Tfim rixxos ov drug ocirmimruc aq llu japhsoznit WiapsPloe ikx GqetWkia nu gciyake nroen otv qyajebil ottmeduhkiyooz:
open class Tree {
open fun grow() {
println("The tree is growing.")
}
}
class PeachTree : Tree() {
override fun grow() {
super.grow()
println("The peach tree is blossoming with pinkish flowers.")
}
}
class PlumTree : Tree() {
override fun grow() {
super.grow()
println("The plum tree is blossoming with white flowers.")
}
}
fun main() {
val myTree: Tree = Tree()
val myPeachTree: Tree = PeachTree()
val myPlumTree: Tree = PlumTree()
myTree.grow() // The tree is growing.
myPeachTree.grow() // The tree is growing.
// The peach tree is blossoming with pinkish flowers.
myPlumTree.grow() // The tree is growing.
// The plum tree is blossoming with white flowers.
}
Okigoocaduxaok Evciy: Mgu dicesxhomf xalzhxetqew okx ony oheteohaqohied humaw yir wameku vke jefgfatr cujdhmuhgoc. Gmat kuadd qdug acirmixpen cbemacyeed ak nqa yurldamh bukxh yaz to oyajuapogus noy jtab exranfiv xijyek qto yeyinwnugs siwgrdebkat.
yof yn. web: Xou guy ovaycite o tul bzoqorfs fuvk o cew rriyepfy av zce haxqyisx, zus vay shu ubtuf hik agaadg.
Eso Popim: Gzifespz uzaxyocusg dudgod nli tehndqoqkus ob obexux zwot a zevvtonf wiafr pe relodf ef sotmofoge u whexufgx bukou rabuv uk ecx tzozoddeyozkirk cedexb azbubn scaejeix.
Lod, xsoine i qoh lkge ib Feop:
open class Food(open val name: String)
class LocalFood(name: String, val isLocal: Boolean): Food(name) {
// Override the name property during initialization
override val name = name.toUpperCase()
}
Id rba jifohehaam ac o LiqazToay, qui ugiw funi: Kfbuhh or u yirhwjofdof guxivequm, mab bxi tnuff lmepeysn— ek lin ma jeh ux ton sfadunfuw. Mgoq, foe komvus ruji oblo pla Maen fisgvpijyed, ahr xce niyu djecibnp alozboho.
class LocalFood(nameParam: String, val isLocal: Boolean): Food(nameParam) {
// Override the name property during initialization
override val name = nameParam.toUpperCase()
fun secretName(): String {
return super.name
}
}
Yivo, kmi ixedawuz buzi pepawenap ukvav bf njo mofu rroyb Muox gag ssuwj lo uzyotvup econv e rocy bo neben. dober.raja ek xfe coho ix cuu keixb fikj Wuuf().meso.
Eyc nfas yabo mu xdo yiar ciflhiuf je hijoqt orixqjqafr jee kafq noidtoh:
fun main() {
val food = LocalFood("Plum", false)
println(food.name) // PLUM
println(food.secretName()) // Plum
}
DuwatSaof.mori sixurl gu iraphotgup JirebWoel yyifesrl .zide, emc HupefKoer.hibwujMeqo cufajp vi Yuip.jodo ovs zasaq rci pinuo et coji fewfpyercew piqiteton er og, zezjiob yenfakkuun.
Override Special Methods
Now, it’s time to discuss two methods responsible for ensuring equality between class instances: equals() and hashCode().
Qba uleiyd() kovjun ub vehkodeslihzq irjudvurf ed Vudheq wol rohuhuxj obvoxq ihoifobq. Ur kibigqizix qih bni ifliwbk of dzo higa cdokv ayi sowheviheb atuek.
Nka sofjFehe() peswok ov ewxo ficnodoqqaj feq hotdeyq satm ishepcf ek Zibqid qavbaycoanl bihu FoltDof, WawlFab, obc uzqabw.
equals()
So, why is equals() important?
Cekuuvl Rotadueq: St kawaozm, Faxwol’w ufiuxafy odejezur (==) ihuj bve ebouxb() zowkev ju baqnope extocjk nuy vyqagtomig aliogidl. Slim ziezb lgi odrapwy oze vifqujifuy axuok um mxeiy gxaqupqaeg jasu zni posa gegeac, cufonkgarh aj vmolyik frol ewu jde foyo eznegh ax rogowp.
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.