An abstract class in Kotlin is a class which cannot be instantiated and can have methods which are not defined.
We will clear the above points with the example :
And thus the class was prepared by Master God:
abstract class LivingBeing(airTemp: String) { var air: String = airTemp fun breathe() { println("Breathes "+air) } abstract fun sound() // The sound method is incomplete. }
Now we can see the abstract keyword used in two places:
abstract fun sound()
abstract class LivingBeing
So, from the above definition it is pretty clear that if a method/behaviour is not defined it should be marked as abstract.
Thus the LivingBeing class is also Abstract because it has an abstact behaviour(Incomplete behaviour).
And since the class is incomplete we cannot create any objects out of it.
In other words abstract classes cannot be instantiated.
Then, what is the purpose of this class from which we cannot create any objects? We will see it below:
abstract class LivingBeing(airTemp: String) { var air: String = airTemp fun breathe() { println("Breathes "+air) } abstract fun sound() // The sound method is incomplete. } class Human(var nme: String, var fd: String, var lang: String, var airTemp: String): LivingBeing(airTemp) { var name: String = nme var food: String = fd var language: String = lang fun eat() { println("Eats "+food) } fun speak() { println("Speaks "+language) } override fun sound(){ println("Humans will speak") // This method is defined. } } fun main() { var human = Human("Rakhi", "Rice", "Hindi", "Oxygen") human.eat() human.speak() human.sound() human.breathe() }
So, in the above example, we have the Abstract class LivingBeing,
abstract class LivingBeing(airTemp: String) { var air: String = airTemp fun breathe() { println("Breathes "+air) } abstract fun sound() // The sound method is incomplete. }
The Abstract class LivingBeing has two methods/behaviours, breathe() and sound(). Outof which only breathe() method is defined.
And the sound() method is undefined or Abstract.
Now the sound() method would be defined in the Human class where the Abstract class LivingBeing would be inherited.
class Human(var nme: String, var fd: String, var lang: String, var airTemp: String): LivingBeing(airTemp) { var name: String = nme var food: String = fd var language: String = lang fun eat() { println("Eats "+food) } fun speak() { println("Speaks "+language) } override fun sound(){ println("Humans will speak") // This method is defined. } }
And in the Human class, we have defined the sound() method(Using the override keyword).
override fun sound(){ println("Humans will speak") }
If the Human creator god wouldn't have defined the sound() method/behaviour the code would have ended up with some kind of error.
override fun sound(){ println("Humans will speak") }