How does an abstract class differ from an interface?
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#):
- Abstract class: single inheritance, may hold state, constructors, any access modifiers, partial implementation.
- Interface: multiple implementation, no stored state; since Java 8 / C# 8 it may have default methods, and properties in interfaces exist in both C# and Swift.
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")
}
}
- Protocol +
extensioncovers 90% of cases: required members are checked by the compiler, shared code lives in the extension, and structs can adopt it too. - If subclasses need shared stored state, use a base class with
fatalError()in the "abstract" methods. Downside: a forgottenoverridesurfaces only at runtime. - Combination: the protocol defines the contract, the base class provides state and adopts the protocol.
What the interviewer looks for
- Being able to say: "in Swift I reach for a protocol; an abstract class only when I need stored properties and must subclass a framework class".
- Understanding that a protocol extension cannot add stored properties, only computed ones.
- Knowing that a
UIViewControllerwith "override me" methods is effectively a UIKit-style abstract class.