Start learning free

LESSON 646 OF 678 · OBJECT-ORIENTED PROGRAMMING

Abstract Classes in Swift

Lesson

TL ; DR:

An abstract class is a class you can't instantiate directly — it's a half-finished template. It can declare methods with no body (abstract methods) that any concrete subclass must implement. Swift has no abstract keyword, so the usual convention is a parent method whose body calls fatalError.


class Animal {
    func speak() {                            // placeholder body
        fatalError("Subclass must override")  // subclasses must provide one
    }
}
class Dog: Animal {
    override func speak() {
        print("Woof")
    }
}


Full lesson:

Sometimes you want to capture shared behavior across a family of classes without committing to one concrete implementation. For example, every Animal can speak(), but exactly how depends on whether it's a Dog or a Cat. That's what abstract classes are for.

Two superpowers

  1. In languages with real abstract classes you can't write Animal() directly. In Swift nothing stops you, but calling speak() on a plain Animal crashes at run time, so you create a concrete subclass instead.
  2. In languages with real abstract classes, a subclass must implement every abstract method. In Swift the compiler does not check this: a subclass that forgets to override speak() compiles, and crashes when speak() is called. (A protocol gives a compile-time contract; you'll meet it in the next lessons.)

Mixing abstract and concrete

An abstract class can also have concrete methods (with bodies) and fields. Those are shared by all subclasses for free, just like normal inheritance. Only the placeholder methods need an override.

Notes by language

  • Swift — no abstract keyword. Use a parent method that calls fatalError, or a protocol when you want the compiler to enforce the contract.
  • C# / Java — keyword abstract on the class and on the method.
  • Python — inherit from abc.ABC and decorate the method with @abstractmethod.

Your task

The abstract-like Animal class is already defined. Create a concrete Dog subclass and implement the speak method so it prints "Woof". The harness builds a Dog and calls speak().

Expected output:

Woof
STEP 1 OF 2
    Ctrl + Enter to check