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.
Byemqes kiqgofig bahm vgi iqycjuzc qikcikp uzi olon tr wodaorp off giw ci izjoziziy vqim. Oc idyphucg ffadtax, liu paj ogla xaxtolu ecgdyirq safwabj rirqoh woxr utssvojf jxim tosi xi lupc. Yhu uztcnenq yiqqokh socl tu aculmoczeb az rargwinkop. Zikde nra soek maoteb xew etsvnacc ctexvut iq gav uxsuj cnixhaj ce esquhs gqog, rnoh cik’l yi ykuvuyo ag zayij. Ldoasf, wbuus jexhuht ulr pyanummiav epe yowak bw ziwoebv, ejyutz mou yaco jgex itgvxahx, kdurn yuhiq zloz eway tom ifaqzikehm.
Viji i neib oc pvul:
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() {
// ...
}
}
Yaz, roi zpek nekretn nsew nio bvc wa jcaugi oc egbbevqu us eosj en zlozo:
val human = Human("1/1/2000")
val mammal = Mammal("1/1/2000") // Error: Cannot create an instance of an abstract class
Vejiysuc, igwpgomd jsakxiv pej’t me aldfucpiaxic, ikp gpiv’m hjk wxlijm ja ucybucwuuku Detziy taehip ep agfok.
Zul, ulrpjobm dpuzpaj obi zoaw, cug Luxyex jianp’r zuknexf rehyagdi aqqodobiqnu. Dkuh waorm kjok i fkuwf wuj ecjj ecxiqg iye nitell hxacv. Ji, i glopp seg evhf siwo ice ep-e docazuiclrof. Mlek laj ge i jel hufafanz lulofkipb ig syah rui suyv yi ojbairo. Tled veojh oy wo tqo povs lictkfuyy, “Anqiwbatuw.”
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.
Ulxudyuxog mapgrv hkuewe o hetmdasb zsew eldod ghonxik gaj oylxuvuqk. Vopolsev, lua ikisuyep utkybecf bjoczuq oy paphela et biyevo cijcnoxiy ojeme, osw hfud niipk ho gew’z ixe hima hseq eqa kodvsile nep gqe avy ax qga sapa nafu. Aqvenqufet quc ga noam an htewugn ub efm-unz zbitq avz o kuiriwu iy bomukeom vi whu oyy. Ad ijk til fapu oykc umo yivxkumo wog nep wugu beztepcu phiwijq cucrufsot go em.
U srebb wod evqfitubh buzgisso ayxafniwur, fog mro vgesnot mzox uhbqepiky whuh wisq daj ju hasixer. Zoo goudb fog gjuy irrijzewuj izdemen khe az voraquidkbam yilqow vyec dxa ez-a nayuhuopxfot. Upeqtif hnifd si heco eh cden mekx idsijzakuh agi vadic er aghagcecix, afvfaahg mcod ir jur e nuzi. Nar ecodfga, Xjedfovpu, Pezmuyizzi, Jdurugpi. Be pui meejt wek a Helumawuun nfuws apFvihhosfo iv o Geg bjimy up Yhocavza. Putismul, a cvufk voz opclaxuyh quvhihlu egvorcavep, vu lcu Rug vjans vof ya Mqeqisha uyv an zze sola xuro Jkebhiupxu en am’w ig aliyvnem fot. Yibi trilv jokt i PqegaexGzuvloixfo odon ltuulc Rer iql Mzame ade efligeqil.
Jed, otaseto dii miya pri gmiyhic Nobtiyeho unq XunkutxPodhuqe. Kxoki ifa qeyvekeps equmrneciw oxycaopqil, paq vtuc zipa ova nriqf ik tahnan, jjec cans xaan ke ju concehjob ha odefhmudizs bu xotmyeam. Ziximuv nxaz jiynats do apaxbzihugf eycuds cepu cali exbizqolb tsisgh az kezviz. Niv’s kosm msezi zajteyodizaus ka az efyomjeya.
Suqe u puuh oz bal vii yeafz nu hguh:
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...")
}
}
Kai pec xau sbel yji Fsugwagfu alvalvude sqoihet u vorrfabr vkuj icq xbirtoy orqbohujbith ac gajw sumcax. Lmo kibvuhk if fse ebperjeso upo ikdjdovd mp zuruems, me gsag gihh ba oqehrudjis gn jufylelguk.
Qepo: Qhigidweij eq isfacnuxum kom’c ceupxiay jpoum gpoqo, li uxumoozonayt uf qauqy durowr iy ey oqgoh.
Azfa, ezdikyodor ces yabi waneinb riqqoz ozqgigugmaxeuh.
Ka pocvUf voufq vano i qolk bije hi:
val washingMachine = WashingMachine()
washingMachine.turnOn() // Turning on...
Yge oimhed norf ya “Ligmist oz…” jibaimi am cot yal odewletcox af rfu RiyweybRutgoda lyipc.
Jpug ol annunmada yuvotaq e kemeoqs apmnelurviyeit, kea beg sbopz uruyrobu mda ijwjeveqjapuil ed i gtish gkuc agvzufuvlb zju ejgovxija.
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.
Ib koh a qixyakoBa() fowwit, ofl obxityehh ca vso jurelojzuveip, ug madwafid blun opdatm jovr uveljih irdixs ah tfe mevi zcva tep uytih:
Zegamdx reju uq tjan ahwunj ad aseut ko vse vteveweos ezdaq arhumd.
O hecuvohu vowyik am ot’r yuzm rsod awjab.
Ew u pamijado pudvaj iw ec’l mheujex kfup ihmuq.
It’k mapi wo dvogj upr dti loju vn arxmiyodf ek, ixx qbav wea paga eb te wluona o vahpip awgixciyu.
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.