DevPrep

All topics › Object-oriented programming (OOP)

How does an abstract class differ from an interface?

Junior

Essence

An abstract class is a class that cannot be instantiated: some methods are declared without a body, some are implemented, and it has stored fields and constructors. An interface is a pure contract without state; a type may implement several interfaces but inherit only one class.

The classic distinction (Java/C#):

The old answer "an interface contains only declarations and cannot have properties" is outdated.

Swift has no abstract classes

There is no abstract keyword. The options:

import Foundation

// 1. Protocol with a default implementation — the Swift way.
protocol Exporter {
    var fileExtension: String { get }      // "abstract" member
    func serialize(_ text: String) -> Data
}
extension Exporter {
    func export(_ text: String) -> String {   // shared "concrete" method
        "report.\(fileExtension) (\(serialize(text).count) bytes)"
    }
}
struct TextExporter: Exporter {
    let fileExtension = "txt"
    func serialize(_ text: String) -> Data { Data(text.utf8) }
}
print(TextExporter().export("hi"))   // report.txt (2 bytes)

// 2. Emulated abstract class: crashes at runtime instead of compile time.
class AbstractExporter {
    func serialize(_ text: String) -> Data {
        fatalError("subclass must override")
    }
}

What the interviewer looks for

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store