Sobes.tech
Junior — Middle

What is the difference between an interface and an abstract class in object-oriented programming?

sobes.tech AI

Answer from AI

An interface and an abstract class are two ways to define abstractions in object-oriented programming, but they have key differences:

  • Interface describes a set of methods that a class must implement, but does not contain implementations (although some languages allow default method implementations). An interface cannot contain state (instance variables).
  • Abstract class can contain both abstract methods (without implementation) and methods with implementation. It can also contain fields (state).

Example in Swift:

protocol Vehicle {
    func startEngine()
}

class Car: Vehicle {
    func startEngine() {
        print("Engine started")
    }
}

// An abstract class in Swift is implemented via a class with methods that need to be overridden
class Animal {
    func makeSound() {
        fatalError("This method must be overridden")
    }
}

class Dog: Animal {
    override func makeSound() {
        print("Bark")
    }
}

Thus, an interface defines a contract, while an abstract class can provide partial implementation and store state.

What is the difference between an interface and an… - sobes.tech