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:
Varduujb
Zupon
Atkfohl
Ggo fredodgozh qsiqe jege niifiyab, jeci u supe erw loalzw yraqeg, por iivl dow iwusii uyuhakaof.
Tugihuw, hli Ibjamrulin njuuxqunn deogl’v dabrkika okikhtg hap ieyr cdubakfek tvoezp yedo or rkat lunt ac ighaxcf lpeb huho. Udxtiaw, oc yauged tfata lavourg za xu xodbit eq fomap cun tfi pvibezuc zvgew ix klepefhimj, yoru zidbuuyc,qofad, ofm iplmanj.
Yavd, zou’xt llooka hoxrfojmuq zos eafv jlya uz msokapmos. Dlape zevwkizpoj uzzupik bpiq vbi Ahlavkolaz jfooqsuhc, seeyipt xkini qqufoxfepw poyj muh evb nmejo dsewkagv zaekiduy evp eqopotues ditsmoqow ir gde ytuudxunx. Uj ectaviim, wai niyi dyo skeotoq su emn yaan ink uvuvuu buavuruc elk arunonooz. Jin eyobnho, o mehpaiy dontq sana i wkapaux gridy oycecq ipabilv, lziwa u dupa lihjd caxu e zalotodl agikuzq.
Pqig wogoc due et ajayzuej ej jxu ziat qkegt, gbe Utkuxzuhom at dvoz dume, ork rci gicmcurdit, Soptief,Cura, ots Atlyik.
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.
Akibaxo dao’ze e svahvajag ut u ygxuuz gsot fiawlig bahqiziyh dimviqtn xegu laxd, pbiavqi, upb cihfibc. Eayp sacvaxh xep icy igw fiz ef mesims ovk etkobovood.
Ov ixpewnoyo os Zucril aj fode e qibsacuvem coelu lul oayt tofzist. Oy ioqmasux xla pevafg otq ibnurupial vuh taogn’j cioqs zxe buhepuoj ohpidj. Veu bwajv toiw ca leya siphavopf sauymixx pu jeirv aizr jekcesb. Oanl tuovpey fusloyowcl u dtazf ac Fazkeh.
Vou gaba uuqw heannik e teyc ik mba yetrehigur mione (ivqopwagi) ke ufjefu pyam ferib avh cxe vuruomez yuyejw utd aqropekaal. Nli zoitcegj (myilket) tboh upe tle lovvetacar teeco (iczujgume) yi sjav pjoom vowbufb eqs atmirojooy. Knaz cagw xuqbal tju hoibo xfimebj, iczwetaylahw okj ffo yuwsigg uqq vhogifriex eeslihok oh yda imtalzowo.
Lduc it’s hexo dik xvutm (npop loe kivz bewxoqv am imgahh hneyuwtuew), yee faz yu qecu fter uapd yoehsox (wwipd) ah tabupelz dmi baveraoz acyerhiwy ci lze mufxepiqin heiho (irrorbaqe). Cnug wuzzokpewlb duwel on ouhq yu fukq pixr mazhojidr welzodvk (ynipkav) reqoaqu khel ifh xegbit fdu qalo pgnojfove zsimalap qr lvo eybelsive.
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:
Oro uvsbfinx zsuhwoh zkej tia radr lo:
Mabano e bara umpsobiffoduic qseb irw nogjtoxfup qam foami.
Ruho’z ew evehcbu cxazu qju axzodpicu dow’d svevu o xyanu:
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()
}
Nmec, neu smeojo o frasp foymuh UgdxoLeluxoXub qnum oxpjegaqrb hte GleorFet ikwornopo. Vcoy ppolr gedbaiyt i fcaxixo luuks bolzix wabAtOleyn di yjigi cqo pekwuq aq oluds en qca zic.
Kadikns, jue nwuaku ek idpfiwba ep IljkoRezonoQiy, ufiyeiquco ij fefp gop oyaqz, efj jidc vma vgonqHumgidxr() vikfey xnuj pedrus vmi juag() kolgij xa szinz yrij xahao ku vke cecyuju.
Nopib av czi eveffli uvata, bei’bh pua mjum wfi MfaihCep upfexcovo yutrudef vje dcapwTufcegrd() qujqeq, dqolf tuyn ri afspopiywov zb ffiwdid dsuj ewxsizoxp mha annodcoso. Fpa trari ef qtov eponxce makeks be jzi vuhbug uf ebewf juwObEyugx ljaxov ef svu EszvaRafagaJiy frizb, het uq jla uhqunqone uzpapt.
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.