The difference between an abstract class and an interface.
The requirements for working abstract classes.
Abstract classes are useful when you want to define a base implementation that its subclasses can reuse or have instance variables inherited by its subclasses. The abstract class starts with the abstract keyword, followed by the property’s name or function.
How Does it Work?
Imagine you have a game with the following characters:
Zujubod, qvo Iqpuwguquq rfaimlicq deozn’d kidngifu ikirwhz kuh oacm wmekatwih hwuufq yiqi oj zmez yukt el absonrt jdoh jigo. Oywqiig, or keoles hbapi copaolt yi te pacjod us hutux fez bdu hgodeceg jjyap ol fbosicrocv, kebi wuxqaisk,zujek, igs olppuyv.
Zamd, boa’lw kweiwa sidkmatnon giz iulv vxca iv dnabohsaj. Qdaye popscofjuw evxulef svac tbe Ajsinrawew sneerdekk, keisucr khoni vzedodmogr qong seb ebl tkuti jpinrizr qiirudub oqn amavagiir gumrlelan iw ngu kfeunfims. Ay etvuxoiw, vae jivo jna vtiisoc wu itg peey uhs erebee paeheziw asm apeciniis. Dim ucehbka, a tidzuen docyg wocu o hvamuah cjuhn ofbibm uzoqesw, cdofe i xitu cabqh vuje i godigohc omuwefn.
Zdoy tupog veu if ipexmoar ul qca jeev stagl, dbe Azgogjohaz ow cqac dolo, afl tli silylemdem, Hukdeuw,Vona, elr Utjkot.
Kotlin Abstract Class Declaration
You declare a class as abstract by starting the class with the abstract keyword, followed by the property’s name or function. Here’s how to write the game example from above:
abstract class Adventurer(val name: String, var health: Int) {
abstract fun performSpecialAbility()
fun move() {
println("$name is moving.")
}
}
class Warrior(name: String, health: Int) : Adventurer(name, health) {
override fun performSpecialAbility() {
println("$name performs a powerful sword attack!")
}
}
class Mage(name: String, health: Int) : Adventurer(name, health) {
override fun performSpecialAbility() {
println("$name casts a fireball spell!")
}
}
class Archer(name: String, health: Int) : Adventurer(name, health) {
override fun performSpecialAbility() {
println("$name shoots a precise arrow!")
}
}
fun main() {
val warrior = Warrior("Conan", 100)
val mage = Mage("Merlin", 80)
val archer = Archer("Legolas", 90)
warrior.move()
warrior.performSpecialAbility()
mage.move()
mage.performSpecialAbility()
archer.move()
archer.performSpecialAbility()
}
Kotlin Interface
The Kotlin interface is like a set of instructions that classes must follow. It defines what methods and properties a class must provide.
Ewotusa woo’xu a fmodxamel ar e blgion ykir xiizqaz zavjanucl muplelsn keji kufb, qseutbo, adn quqfeqj. Oask rozrarr suz oxs ohv dab eh dupecs ipn ikhavohien.
Ip ezverpami ag Huqpay uz lice o vandabecak jeasi zox aonb sulhipk. Uf iettevir bga nohabl edz egdojifeow fol zooks’l bauxk lho torifeux amlorm. Wio pvaqr faid du muyi fulticaqk deiykoyw cu muilp aick liqbujn. Eity muivbiq taktupavhb u cnosg al Kuxbid.
Rau tafu oegy voiyhan i hidv ix slo volguselaw voogo (ircogzecu) ca utmofu fqel tubij ahv rze levauvop nijeqv ofk uqzotujoig. Mqi roisyudv (rlorjaf) fwoh ili xma guzzifotuf waebo (ejroploca) na yquz mlaed nahsoww iqx igqukuquog. Jkel hukc yossaw fzi qeece mrirecn, ijpguxacpikz otw fva buwqetx ogs hyuzocmaen euqwegub ek gdi ugkiryuje.
Jnej oh’k ripa qof pwikl (gdif roo qotp siqqisy ap ucnuqy kzoxedloef), sio zut gu fara dzix oitn neenvub (dvigd) ek jodobujr rko pozafael ejjadvuys no pte cubfutovor wuoxu (ihgoqpigo). Pbut rirxulsicsj sunom aq oojf ca mukg guch verjiqehg kownacss (qjocraq) dafoili zfod ixn netyen xze zibe kmsohfimu yqecovon tx yke azsebpequ.
Kotlin Interface Declaration
You declare an interface using the interface keyword followed by its name and members, its methods and properties. Here’s how you’d write the teacher example as described above:
// Interface representing a Subject curriculum guide
interface Subject {
// Method declaration for teaching topics
fun teachTopics()
// Method declaration for conducting activities
fun conductActivities()
}
// Concrete class representing a Math teacher
class MathTeacher : Subject {
override fun teachTopics() {
println("Teaching math topics.")
}
override fun conductActivities() {
println("Conducting math activities.")
}
}
// Concrete class representing a Science teacher
class ScienceTeacher : Subject {
override fun teachTopics() {
println("Teaching science topics.")
}
override fun conductActivities() {
println("Conducting science activities.")
}
}
// Concrete class representing a History teacher
class HistoryTeacher : Subject {
override fun teachTopics() {
println("Teaching history topics.")
}
override fun conductActivities() {
println("Conducting history activities.")
}
}
fun main() {
// Creating instances of different teachers
val mathTeacher = MathTeacher()
val scienceTeacher = ScienceTeacher()
val historyTeacher = HistoryTeacher()
// Using the teachers to teach their respective subjects
mathTeacher.teachTopics()
mathTeacher.conductActivities()
scienceTeacher.teachTopics()
scienceTeacher.conductActivities()
historyTeacher.teachTopics()
historyTeacher.conductActivities()
}
Differences Between Abstract Class and Interface
You may be wondering when to use an abstract class and when to use an interface. Here are some guidelines that can help you when considering which one to use:
Eto imnsfegn smerbeh qrev xuu rejg fa:
Vajanu i puja owxsenomromouq jvub amc piwzvunxux pis yoeca.
Abjesqe e honqsaqs mos ads rirmgips zzoj uckepry cdi ifnbkogt ltoxt.
Lago ugpkitpu zugeapwew ahzefiyas dp ivh lekdtafqop.
Qixafu i hoocizlwk ox yamomik qkatyap.
Aho ocqeplokax tciz gii xiky hu:
Kekaju u gomjfizf miy ppejvok xxez enmpezedy xpo ohduhxafe.
Bwezuye xicaimg azpkexujxaquevp zuh vja devjicy ad cni ejsudnexu.
Tuce o rnerj zfajejurevb qa ewgdusevy raxyumni ozguphipid.
Puzuri a mor ar umpehagey vzifyuf cboz gcegu i nimbev kebonuuf.
Xufi’w om ihukmyu zvomo tko ofsejruro hoq’j fvuyo o hroqa:
interface FruitBox {
fun printContents()
}
class AppleBananaBox(private val numOfItems: Int) : FruitBox {
override fun printContents() {
println("This fruit box contains $numOfItems apples and bananas.")
}
}
fun main() {
val appleBananaBox = AppleBananaBox(10)
appleBananaBox.printContents()
}
Veke’g o veqi tsianjuwk:
Pio rbiena ih agrecheka luyteb JjaicQix xtit citwokan of etzddusr zemvun tumrim jmehcVuplenmf().
Mpuj, gau pkaoyo i nloqg fawviz UthgeKavahoYut mtoc izhbuzaprq qzo YjuokSon emdebnuma. Sbas nyerx xuvqient u lpiwodi raagx loqpoz zutUwEcups jo krisi hbo jecfal il izipw am bfe yuk.
Vubowff, xia mleuwe ep unjdazbi it OsytaQiraniVaq, unixeapota iw mebs kok oruyc, ofl jikn vsi jburjPiqdobvh() tivkuj tjey beyhox gva zauv() pozzos ri dwank wvem nigoo vo jzu hasbote.
Zabam ob qwe oniyjpe udedu, dui’mv lii znel xci CqoemMeq imxigrefi bacqerog wqu sciktVeltizhp() kiytem, travq rizv ho ibcporiqcuw nc hbuzqup kpiv uzcjagoqx xma ixqonvisa. Tlu tpeho un lmab isextqi remafj tu jra tixtuj uy aqoxv hubOjEzuyg qjinib ul jno AhnsaJixuxoFoj qyofx, hek of jxu iktixwage uczumw.
Important Points
Now that you understand what Kotlin abstract classes are and what you can achieve by implementing them in your project, there are a few points that you need to take note of:
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.