โ 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())")
}