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
- In languages with real abstract classes you can't write
Animal()directly. In Swift nothing stops you, but callingspeak()on a plainAnimalcrashes at run time, so you create a concrete subclass instead. - 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 whenspeak()is called. (Aprotocolgives 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
abstractkeyword. Use a parent method that callsfatalError, or aprotocolwhen you want the compiler to enforce the contract. - C# / Java — keyword
abstracton the class and on the method. - Python — inherit from
abc.ABCand 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:
WoofFree plan: 30 tutor messages. PRO is unlimited.
