DevPrep

All topics › Object-oriented programming (OOP)

Inheritance

Junior

Essence

Inheritance is the mechanism by which a class receives the properties and methods of a parent class and can extend or override them. It is an "is-a" relationship: a Circle is a Shape. Inheritance gives subtype polymorphism: wherever a Shape is expected you may pass a Circle.

In Swift

class Shape {
    func area() -> Double { 0 }
    func describe() -> String { "area = \(area())" }
}

final class Circle: Shape {
    let radius: Double
    init(radius: Double) { self.radius = radius }
    override func area() -> Double { .pi * radius * radius }
    override func describe() -> String { "circle, " + super.describe() }
}

let shapes: [Shape] = [Circle(radius: 1), Shape()]
for s in shapes { print(s.describe()) }
// circle, area = 3.141592653589793
// area = 0.0

Benefits and cost

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