โ† Back to OOP Concepts
๐ŸŒณ
Pillars

Inheritance

Allows a class to derive shared state and behavior from a parent class, forming an "is-a" relationship.

The Problem

Duplicating fields and methods across similar classes leads to maintenance headaches โ€” a fix or feature added in one place must be manually copied everywhere else.

How It Works

  • โ€บA subclass inherits fields and methods from its superclass and can override behavior
  • โ€บModels "is-a" relationships, e.g., a Dog is an Animal
  • โ€บDeep hierarchies can become rigid and fragile โ€” prefer composition when the relationship isn't truly "is-a"
  • โ€บAbstract base classes define shared contracts that subclasses must fulfill

When to Use

โœ“Multiple types share common fields/behavior with specialization (Shape โ†’ Circle, Square)
โœ“Framework base classes that provide default behavior (UIViewController, Activity)
โœ“Modeling natural taxonomies with clear "is-a" relationships

Real-World Examples

๐ŸŽ
iOS

UIButton inherits from UIControl, which inherits from UIView

๐Ÿค–
Android

AppCompatActivity extends FragmentActivity extends Activity

๐ŸŒ
Web

HTMLInputElement and HTMLButtonElement both extend HTMLElement

Code Examples

Swift
class Animal {
    let name: String
    init(name: String) { self.name = name }

    func makeSound() -> String {
        return "..."
    }
}

class Dog: Animal {
    override func makeSound() -> String {
        return "Woof!"
    }
}

class Cat: Animal {
    override func makeSound() -> String {
        return "Meow!"
    }
}

let animals: [Animal] = [Dog(name: "Rex"), Cat(name: "Whiskers")]
for animal in animals {
    print("\(animal.name): \(animal.makeSound())")
}