Abstract classes vs Interfaces in Kotlin

As you may know, interfaces are just abstract functions but with subtle differences.

Abstract means two things :

  1. this class can’t be instantiated

  2. this class can have fields with no implementation (abstract fields like abstract functions or abstract properties)

Now we’re going to talk about the differences :

  1. The normal class can inherit from only one abstract class but can implement any number of interfaces

  2. interfaces can’t manage state as they can’t have concrete properties like this :

interface Thing {
      val thing = 1  // error Property initializers are not allowed in interfaces
}

but this is valid in abstract classes

abstract class Thing {
      val thing = 1

3. interfaces can’t have protected functions but abstract can

protected : it’s an access modifier means that fields can be accessed only in their subclasses.

so this is invalid

interface something{
protected fun something() = "thing"  // error Modifier 'protected' is not applicable inside 'interface'
}

but this is valid

abstract class something{
protected fun something() = "thing"  
}

4. Interfaces can inherit from other interfaces, using the same notation as one uses to inherit with classes:

interface Base {
fun foo()
}
interface Sub : Base {
fun goo() {
// do something
} }

However, an interface cannot mark an inherited abstract method as final, even if it provides an implementation. So, this is fine:

interface Base {
fun foo()
}

interface Sub : Base {
override fun foo() {
// this supplies an implementation
} }

but this is invalid:

interface Base {
fun foo()
}
interface Sub : Base {
override final fun foo() {
// this supplies an implementation
//error: modifier 'final' is not applicable inside 'interface'
override final fun foo() {
} }

Abstract classes, like regular classes, can override inherited methods and declare those overridden methods as final, to prevent further subclasses from overriding them.

Thanks …