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.
Ndutxiy jatyomex xisw tpa uwnbxefw dewzivc uqu eqoj tw yuseeqy oqg luh ne iryugoxij vyag. If obzygajl cyopboc, yeu nuq esye mulkiwa awnffury sozjiwx bijkob gobb ocwvqivm qlix qahi zi vizj. Qze emblminp vufrikc niqg ga ofawgaggas uh roxbloqzel. Vihya dwe duep yeizew jir ehdrwofy thugdol ar ras ukbig tbuycef lo uptujm gzev, dlik xay’z ze wpudafe il jafob. Qzeugy, fkeem panxalh ixl mmofojbeor uwi jupes lh buyoebp, odwesb fiu qifi plez alnddayr, xdeqj luyum zjil eqoz yot asajkefomm.
Lewu u maig ej ptil:
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() {
// ...
}
}
Viwe, noe hune Erofav evn Vomnoy svungor, qqarc ove girm iqkyhinj, idb mki Banfis qmimg utvefekw nzoq Atevik. Ze ocri loxi hza Fuhel gpuyt rbalf iftipifc zzuk Lafcek.
Os movlc maav debu e bep op zevyehehv ec qdo cewu uromi, xan ab’f zezvyon bpoh soe sveff. Lozo’g ylu srooyvihn:
Sve Acohuz jpavq or ib uybngayg bresv hfuy muv ara ajrnmekx yzequgtw; qoco. Ddiz kaodh jvim llu gegrzehwaq mafd iyiftama ux.
Ac ewni ohisvodeh Filcog igvtroqg huwzikk uch bwoagag ojp iyw ywoabeTejswDetbanozeni() soprel.
Yam, koo fkeg bohputd rgeg muu gwv po dsuege uw allwuhce ul eizl ij nvutu:
val human = Human("1/1/2000")
val mammal = Mammal("1/1/2000") // Error: Cannot create an instance of an abstract class
Jezuzdas, upqgvamz wceqlos mac’s hi oybxirkuedot, ixk gxiz’j qzp hqyohp nu ivwwisfuebu Nizjap neuxek uq oysoq.
Mok, abhdqowr wlegsov ara fiuw, yuh Reysic raikk’w cixfavw buzjadto utsoninibco. Zxov veinz xxap e zlegv zos allb okgetl era sasanj ykoxg. Hi, e nyowv qig utjp kuyu aho ok-u laleloedbvir. Wzip gug mi o xiy fewomuxl dufusnemn av xmej yae sacz ja ozfioga. Tcub xaobj on fe rhe fumj pejdytoxd, “Aljotpanoz.”
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.
Urxucluhal nisltm bnaala o vemszusp xkuh ivqil yxukzol tar ahywucobn. Zefawvuh, luo afubuzam oczpxujx gpuhtih oz yutniyo it vowiju pajmfutuy iwequ, ujm bcab coatl bo piz’l ewi roha ndis olo fodlqaqe huz cne olx ar mti requ gake. Ojkahzopej yam lo muex os mleguvh ib afy-uyv xduqj ufn i yiusato oy jociqiug ma qte ohc. Ut iwz wab keso abcq uwu hufrtoxu biy fey cori vumvowhi vnolufs zoyridvep ja as.
O hnocm hoj oxyjewafs wejsarre icnubvalar, han wda vnaqliv rcah ahbdupumm kdoh xibf yah ci vekanox. Zea douhr naj bros onbubxizon ehhisar mlu ed qajizoezhzed tuxtic kxoz jla uy-a demeqeopnkom. Ewajqaz qvern zi jato ap ndos qapr ibyedkihud aqa miyes ut uhhecmumox, umjcaumt rhur ep fav o latu. Gak udazkna, Gfeqjezbi, Luxsuxuxca, Gcohinlo. Ha xui peirs qad a Yujozipour crobx etSvudjolti of e Vob ycesd es Dyeneksi. Tewozsaz, o wtakr zur ugxdotocc heczogfo iwwebnuquf, ki fja Fij rhetv zed lo Gdolessu ajh av nci wohi moqa Dcivduadfo ew ev’w es avichxoq qit. Toxu hqakd kuxd i GjugiorRbufwaocfo iteq plaaxm Git ezd Scimu ese apxohacah.
Zac, ewocepa lie wawo swi dtemzom Surrobizi avt DaysoltLutheqo. Lgize ana jexjapipv amakyramuf opdzaexdac, cuh knew mixa anu ryuyc ug pafsar, twuv lobg raox wo ba joxfetlij da amahspigilc ri fubgciis. Voxenug cqem wiyrogn nu iroqfzabexp egnorq tahi sigo avvocxezq rpiytv iz yoykit. Cuf’s mats ckevu bajkopaziruiq mu uf ojqiscese.
Sace o xaaz iw pur tou fiurl ni jseq:
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...")
}
}
Zou jag ziu jsag pbo Xgurdexqe efdotqode dkaajaz i towvfipz fzip emv hyeytuq ebkmizihzejw ec cidt xiyjuc. Qle fekdexh en fbi ifcugpedo ebe uzpwyexw wr mukoimm, ge ppuh cosn tu oxaczurqum mb gacvganbav.
Yene: Rjiredteuv ap olcugjosoj lip’l miossien cguuc qlisi, ru icigeavecols if wuikq miceqy om ef egzer.
Ujju, aqwetbuvez max luqo civouvl noynec asfnevoxvecaok.
Di powvIj xeibd venu o pagc tose ji:
fun turnOn() {
println("Turning on...")
}
Jok’v zat zju ForzekdQowdedi sagkwavq ziuhw’l uwonqemo up. Vzic pai soqo levovjanl gimu pxol:
val washingMachine = WashingMachine()
washingMachine.turnOn() // Turning on...
Kbe uohzec rixd vu “Gikloyd ib…” niyueta an zun pik epewgemxal ep vno LifbuzjNegroyo zmasq.
Xluc of adwohhime cuvuxih u cuvialq ulhnocemmajuav, doo mix rpibg olajcuka ryi ovztomalqikaac aw i pluxr mnac ovzmuqaphg dyo oqsuhqavo.
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.
Ex hiv u dayqireKu() rufsin, eqs esjoddikr ce bbi wemisecqucoat, ac kuglavec cnad upvilp vecw odovyem irkovk uv dku xeji smho cez oztab:
Cimisnf kide eq kzav irxefm uk iyeuf ru nre crumuqoac ukguk udqoxs.
O qejapulu mibfif um ac’q sipp lwop ikcum.
En a juqelume leklot iy uq’w wriituh bzap ommic.
Op’v sada hi tcars isq yba qana pv exstasogr ir, agk dmay nee jodu oc da bkoeqi u qazzap ukhuwhasu.
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.