The concept of interfaces in Kotlin

The concept of an interface is used to define behavior in classes selectively. For example, Cat and Lion can be considered as Animal. But in common practice, Cat can be a more of Pet than Lion. So adding the pet behavior to Animal will cause problems, as all Animal instances will by default have the Pet behavior, which could be dangerous. This is where interfaces come in handy, as they enable us to define behavior selectively as follows:

interface Pettable {
fun play() {
println("Playing");

    };
}

With the preceding interface named Pettable, the play behavior can be introduced selectively to classes. For example, Cat can be given the play behavior while Lion can be excluded as follows:

class Cat : Animal, Pettable {
var noise: String

constructor(noise: String) {
this.noise = noise;
}

override fun name(): String? {
return "Cat";
}

override fun makeNoise(): String? {
return noise;
}

override fun play() {
println("Fur Ball");
}
}

Kotlin has simplified how a class or an interface is being used in a subclass, and the syntax remains the same.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.138.202