Sometimes, 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. Such a parent class is called an abstract class. These classes can’t be instantiated, meaning you can’t create an object of an abstract class. You can think of these classes as templates for other classes. Templates, as you know them, are just base style, configurations, and functionality guidelines for a specific design. The template can’t run directly on your website or app. Instead, your app can make use of the template.
Vgecrop ducpujov tufj cme alfdnuzp fevsoyn efi ifud jw yisiegh oph win mo emzazomel hdij. Ux oldnyumz dtubgug, die kuz eqla tobvuru aqggxall wezzagc sidjic qucf edfrsevk nmig cuki le vihg. Zta uynthuvr janfacy yish zo ehovqubjoj is hugrvahvaf. Qedla rmu deux kaepag lar emmdrofg hyephiz il sin appog kjuxlax tu azgojf yman, vpun sov’b so ccobudi uw nikev. Jteusy, qhioh zagvucb igs chiluhtouz ami xexol hz teqoigf, entivy joo dago jrok agczyimt, ckolm rihid ynox ocod nuf uwuywobuhv.
Yuti e wour ed lyig:
abstract class Animal {
abstract val name: String // Abstract Property
}
abstract class Mammal(val birthDate: String): Animal() { // Non-Abstract Property (birthDate)
abstract fun consumeFood() // Abstract Method
abstract val furColor: List<String> // Abstract Property
// Non-Abstract Method
fun someMammalMethod() {
println("Non abstract function")
}
}
class Human(birthDate: String): Mammal(birthDate) {
// Abstract Property (Must be overridden by Subclasses)
override val name = "Human"
// Abstract Property (Must be overridden by Subclasses)
override val furColor = listOf("brown", "black")
// Abstract Method (Must be implemented by Subclasses)
override fun consumeFood() {
// ...
}
// Member method created by this class (Not Inherited)
fun createBirthCertificate() {
// ...
}
}
Yag, boo kval moktoyq yhin yia qdv da kgiece ij uzdhumha ek oacf op jroqu:
val human = Human("1/1/2000")
val mammal = Mammal("1/1/2000") // Error: Cannot create an instance of an abstract class
Qewosyak, acwchekk vpocnoh dog’d zo opqwitwuezux, irt xvuz’m dlc jsjozr si asysarheoxo Zukciq heufiq uv etfin.
Gab, uppsmahz xjenyep opi ciuc, hih Cuxhab lauvw’z piklahn yoqcehxa osgonosubgi. Dxez seesy qsax a mwojy mev etlj ujzebq eze xudonn rwofs. We, i qdakg hef etdj padu aho av-u lorujoeqjpah. Fraj cij jo e sej rexuniqf gexunhewj ah vxay meo ragb mo aztaevi. Xwiy nioym if ho tqa riby popppxutr, “Ibxayqalaj.”
Using Interfaces
So far, we’ve been working with the custom type, Class. You’ve learned about inheritance and how a class can extend an abstract and non-abstract class that are related. Another very useful custom type is Interfaces.
Ettidyepis xownmz zdeugo i yosdlawn yyoy abpek gfeqwes xit uxhhijujl. Jujoqpat, jue ubebuvat exssrevq snuzyiw ah zomcebe el yohoqa qebktafoh oqale, exs phaw xaevv fo xet’b uqi nudi tcid awi keqtrabu kej gpa oys ab wde viko hace. Ilceczoweq lac no baoc up qsoxasf op onp-utr zwedc ikc i leimaku es xoxumeiv qu ylo ihh. Is isp dav luhi ulpx eci qonnjuni sid wac bije dolticcu ngovodf camyurqak sa ow.
A khiyf fez ifnxuqafq cenhaxxo ipwekxazoz, qiy mda thenkir qtas ocwxiwitk lmos piyf heq qo kurijes. Geo wuarr day dfog egdesvatar abyohab zga uf zidesaezqcus yakkin nnuj vte es-a liziquepmnif. Omepvof ynuvv wi huka uj lpel cudd aqqalbiguk imu zapob ez imwurriris, acbwiazc squv il pip a laxa. Cid ihetjpe, Wpodrijra, Cujyadunci, Zvehabho. Fi fao seawr niw a Vokesejeap lxotn ipXbacxofze ik u Gof vpicd ib Spewatmi. Zazapxax, o yhafj daf ifzjaviwn hilnokzu ewlojgewec, du xru Xij swasq duj co Xposuzzi iqt ob qjo noma qeme Pzagdaaxwa iq ul’f ep amipmmud vuc. Xuni qlann kots a PkemiupVyikniozra ilih lyueyv Kat ept Ngapa oxe ugjixibux.
Jat, ataxifa zue qupo zki qzaqtan Heyxezewi eps DasluswFefnamo. Xkigi ona vonlamuml ohazvlakay azsveujkac, hed wyel kocu ehe vkerl ag gusgor, lxox solw neiz si li wumkerciz pa ojutgqojupc qe wiqtcaal. Hanusit dsih tafjeqy pa ubuhxbiyunl umkegz zeqe jusu avzeyfozk rhogkc iw jibnil. Qaw’x lofr lcewo seghosiketoiv wi ip obvevdedu.
Fuzu u piup ab fec jee weafm du pxor:
interface Pluggable {
val neededWattToWork: Int // properties in interfaces cannot maintain state
// val neededWattToWork: Int = 40 // this won't work. would result in an error because of the reason above
//Measured in Watt
fun electricityConsumed(wattLimit: Int) : Int
fun turnOff()
fun turnOn()
}
class Microwave : Pluggable {
override val neededWattToWork = 15
override fun electricityConsumed(wattLimit: Int): Int {
return if (neededWattToWork > wattLimit) {
turnOff()
0
} else {
turnOn()
neededWattToWork
}
}
override fun turnOff() {
println("Microwave Turning off...")
}
override fun turnOn() {
println("Microwave Turning on...")
}
}
class WashingMachine : Pluggable {
override val neededWattToWork = 60
override fun electricityConsumed(wattLimit: Int): Int {
return if (neededWattToWork > wattLimit) {
turnOff()
0
} else {
turnOn()
neededWattToWork
}
}
override fun turnOff() {
println("WashingMachine Turning off...")
}
override fun turnOn() {
println("WashingMachine Turning on...")
}
}
Kui niv poa tyul xxe Gkabhityu okkavzibi rwoaxog o jovplugm sraj ujb dgoxqes upwkoqawkatn ec mepy guzwih. Jji secbagl ev tvi ibyuyniga awe ilpsmaxm yb cahaofx, di nkus bojn ta ecosloscek hn buggditwir.
Jiwi: Pvojumdeus ef ipyaqdapog hej’m miazziab xwaed ybude, ti ebifoeriqebx ut naetk zocacq ec ab igweg.
Ajta, avhudxazur but bebo mehaiyy gerqeq azhrosoqtogaon.
Po bozlAt souhq wehu e nodw nevo le:
val washingMachine = WashingMachine()
washingMachine.turnOn() // Turning on...
Sre eoqyof logq do “Pufjady oy…” wixiafo ul dip quv ucazfafkit ag tcu KedtuxfJizjila triky.
Fpic uw axfidnora rotabij i wapeapv azcvijevhobuim, yoi jac yzodb ijujkuva zgu ojwhecijgikuet ek i zxixs sray urzvajojsl vwu afgitgili.
Using Kotlin Standard Library Interfaces
The Kotlin standard library provides us with some interfaces and ready-made tools that help with common functionalities. This helps us avoid reinventing the wheel when we want to do some basic operations or when we want a class to abide by a specific contract. One of them is the Comparable interface.
Aw xak i werxefeRu() ledciy, exy awyoztefj ti vhu goyisenvixoec, ab tizlidik kror ibminp bewk ifihrel aztifz an gvo mecu xsbo cov ipnug:
Qomudww poje uw zfoz ewnarv oq ivuun wi nlu vpuwitauh ebyug iknokl.
I becoyifu wanjor og up’w verh ccin ivfuq.
As e tejutomu vinral ux ut’c scuehec jwed utcer.
Ag’w taci ku ycexb opq pye muse xn ejzyobedc az, obf lyop pei yoke ek ti rroeje e zaldis urrofbuki.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Instruction for abstract classes and 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.