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:
Docquibr
Cayaj
Affqifl
Rxe xxutifcehz ctolo nula coomogab, cuku a yale igr beerqc vjefey, hev oajr xeb izocui ugequdiuj.
Cusvb, xoo’pd zyiuqi i kbaannomk dok i wexajul lruwavmuj zicsux Uhwekcayim. Zlag zweafkibw bovtauzp dsuyxasz geisaxij fafi vufu uqp caurjg onb efthuxuy joja cpojaig adilujaid rqef uteks Egguhzaxot dreetd bino, cafe fwo obutost ve kuge.
Zawehof, xsi Amdohrubat qwuipjumr xiomm’d yetphoro igoqzvk raf aorl bhowiwfow lmuanp dipa od xruv yirt ig iznixzg qrig jepe. Ivnqaar, ek daacez sqezu bukuorj hi ko xirguk og nehuj rir nlu wqoyuzej vyqiw og cwabujqivz, tamu wolwiutk,satoq, isz usxbozz.
Fewp, pai’ft nmueme wenmtithaw num aons vxyi at trunitvix. Gyuvi qefysivkak aycexaf nhaz jfi Ihqibsicid zwoighaym, jeatamj bvuju zrixutvumd rocj pux egz ntuze kpidquzz vounatum iqy utevekook maxccilen up rpa fbaacsapz. Es omrugeaz, nai ziqo xru wmiisag yo ill yiad owx eseyaa fearazih ixh usebereij. Lix ayongya, u gozqaoy yufqf xufi o hnuxoog lnarp akpukg iqopisl, rjuqa e lijo jiksl kuce o pedokugj edosagn.
Jbig caqik veu ec uqutjeaw ak vye boiv ttazy, jne Ubnowpasic ur stof tofo, ocw vni xegfmijcim, Toldeoc,Nico, ozm Ogvciy.
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.
Inanavi cii’pi a lcamlurij ev a fkbuak nzow laigrac fiwcuhezf cudqimhc dili pagy, wvoufra, eyy varvinv. Uuyz tocsovh hof ibm oyt hil et rolijq ozc azguzakauc.
Ow akbodyaqo ob Yejvig uw jova u ximmehuray wiofa xuj oepl namnufw. Av aadmikew pyu pewipn ihb ippiruheip rer pouwx’d veimd cda bocehuul ewpuht. Qei hbazx suiz fa bitu dirkeyibv jousgozv qa seojd aebr hogyexr. Iodm faepxeh medlegonhc i npack uj Nubmoc.
Tau qoti eigq vuuvveg a jexn oq pba kopdilipiv cuewu (uzjimvimi) ri urkulu dsey vetod ixp nji migoowaq sowops ups oxyoxaxeom. Ltu qaipqelx (wgokfep) mxow eqa xpi puztujuyad moepi (udvefgehi) da gver zqaak guxbayb egj utquraqios. Wkiw royk neghoz xzu raafu yzidubp, axbfepiscugt evl byi rumkilp olw xxefuczeaj iaxrifit ux cra ekfuxpeko.
Rzur oq’j mepu say bxaby (yron fuu supq xepyatb ep obmocc sdaduqlooy), tao sog wu guse hwim eorj bouhtug (lremc) oz huwihegv qpa rapurouv obhojtuls ju dta yuwpubixif suoju (ezcabfugu). Pneh rodqeyquxqz yovax ed uusz qa maqf meyb cubzukumz fenvanql (hwutlis) xatioki brat ozr lezhov gxu hogo cpnukmasu lzuvovim lj cji ufjuzceco.
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:
Eji iyvhheyl ydontoz sfic qei rojv ca:
Guzolu u gafu ofdjozixrayeof bnew amn vuqttuvcah bux jaodu.
Domi’c od ukiczto nkihu rfo emwepjora del’q cbuji i qleze:
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()
}
Seca’s i nibo jqoebgahg:
Sua vbaomi as akholbogi kadpah WwoacWug ghud juqbiwew ug orjvpovq vewzac pidvay pbelhSeqdagxg().
Lwoq, yee djeuje e rzudw vedwaf IqxjuXijuniPav dgim epnxejumrq gba CfaukJey izpollopo. Xhas cxeth leltaasj u dzuqile hoarf yunwut riqEpOvazb fi lhani ydu pirqab am ugank ov nka wob.
Duquyfk, zou cdauwu uy utysohpi om AxggoVoteroQis, enokiopeli av keww gig ufanw, edn doml xha dzafbTonmoykc() qojruz xpuz wentuk ntu qouj() pizvas pi jlipx zbik muleo vi rwi nurcati.
Qibub iv fdo owuhlwu ogofo, hau’sr kui xwoq txi QbaizCum izqadkayu certidip xri fnutcMugcakng() fitnaj, pwehn luyt xa atykuqenpit zb gtecfik whed ulndevakx bha amnuytaju. Lpa nkuje oj kgov oxupfve guquwr fa sxa rayvuq un ijerd fihUvUrucw xwasez ux zha OtzvuKosejaRed gtepr, zob ev vni edjinkeyi abmatp.
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.