An interface is like an abstract class, the difference is that an interface cannot store state.

Interface Declaration

interface Cats{
fun doMeow()
}

How to use Interface

interface Cat {
val sound: Sound
fun doMeow() = sound.meow()
}

class Siamese: Cat{
override val sound: Sound = Sound()
}
class Persian: Cat{
override val sound: Sound = Sound()
}

class Sound{
fun meow(){
print("Meow meow")
}
}

Note:

  • An interface can’t have a constructor and cannot inherit from a class.

Multiple Interfaces in a Class

interface Cat {
val sound: Sound
var color: String
var weight: Double
fun doMeow() = sound.meow()
}
interface Animal{
fun kind() : String = "Undefined"
}
//Adding new interface in a class using ,
class Siamese: Cat, Animal{
val kind = "Carnivore"

override var color: String = "Black"
override var weight: Double = 3.5
override val sound: Sound = Sound()
override fun kind(): String {
return kind
}
}
class Persian: Cat{
override var color: String = "White"
override var weight: Double = 4.0
override val sound: Sound = Sound()
}

open class Sound{
fun meow(){
println("Meow meow")
}
}

Interfaces can implement another interface

interface Cat:Animal {
val sound: Sound
var color: String
var weight: Double
fun doMeow() = sound.meow()
}
interface Animal{
fun kind() : String = "Undefined"
}
class Persian: Cat{
override var color: String = "White"
override var weight: Double = 4.0
override val sound: Sound = Sound()
//this will be redundant if you dont assign new value
override fun kind(): String {
return super.kind()
}
}

I’m still learning, please leave a comment if there’s something I need to improve/learn/elaborate. Arigato!

Android Developer | Newbie