What is the difference between abstract classes and interfaces in Kotlin
In Kotlin, both abstract classes and interfaces define contracts for implementing classes, but there are some differences. Abstract classes can have constructors and also have implemented methods, whereas interfaces cannot have constructors and only declare methods and properties to be implemented. A class can implement multiple interfaces, but can only inherit from one abstract class. Here are examples of an abstract class and an interface:
// Abstract class
abstract class Animal(val name: String) {
abstract fun makeSound()fun printName() {
println("My name is $name")
}
}
// Interface
interface CanMove {
fun move()
}
// A class can inherit from an abstract class and implement one or more interfaces
class Dog(name: String) : Animal(name), CanMove {
override fun makeSound() {
println("Woof!")
}
override fun move() {
println("Running")
}
}
