Sobes.tech
Junior

What are the main differences between a class and an interface in Kotlin?

sobes.tech AI

Answer from AI

  • Class: can contain properties (states) and functions (behavior). It can be abstract, open (for inheritance), or final. Constructors define how objects are created. Supports inheritance from one class and multiple interface implementations.
  • Interface: defines a behavior contract that classes must implement. Can contain abstract function and property declarations, as well as functions with implementations (Java 8+). Cannot contain states (properties with backing fields). A class can implement multiple interfaces. Does not have constructors.

Comparison table:

Aspect Class Interface
State Can have properties with values. Cannot have properties with values (only abstract).
Constructors Can have. Do not have.
Implementation Can provide full implementation. Provides partial or full implementation (with default methods).
Inheritance Inherits from one class. Implements multiple interfaces.
Initialization Can be instantiated. Cannot be instantiated directly.
Type Concrete or abstract. Only a behavior contract.

Example of a class:

class Person(val name: String) { // class with constructor and property
    fun greet() {
        println("Hello, my name is $name")
    }
}

Example of an interface:

interface Greeter { // interface with method
    fun greet()
}

class EnglishGreeter : Greeter { // class implementing the interface
    override fun greet() {
        println("Hello!")
    }
}
What are the main differences between a class and an… - sobes.tech