Subclasses
Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 22 of 57.
Inheritance lets a class build on another one. class Dog: Animal makes Dog a subclass of the superclass Animal: a dog has every property and method of an animal, plus what Dog adds:
class Animal {
var name: String
init(name: String) { self.name = name }
func describe() -> String { "\(name) is an animal" }
}
class Dog: Animal {
func fetch() -> String { "\(name) fetches the ball" }
}
let rex = Dog(name: "Rex")
print(rex.describe())
print(rex.fetch())Output:
Rex is an animal
Rex fetches the ballA subclass that adds no stored properties inherits the superclass initializers, which is why Dog(name:) works without an init in Dog. Inheritance models an is-a relationship: every dog is an animal, so a Dog can be used wherever an Animal is expected:
class Animal {
var name: String
init(name: String) { self.name = name }
}
class Cat: Animal {}
class Dog: Animal {}
let pets: [Animal] = [Cat(name: "Tom"), Dog(name: "Rex")]
for pet in pets { print(pet.name) }Output:
Tom
RexOnly classes support inheritance; structs and enums cannot inherit. A class has at most one superclass, but a superclass can have many subclasses, forming a hierarchy:
class Vehicle { var wheels = 0 }
class Car: Vehicle { } // Car is a Vehicle
class Bike: Vehicle { } // Bike is a Vehicle
// struct Truck: Vehicle { } // error: structs cannot inheritPut what all subclasses share in the superclass, and only the differences in each subclass. When one type is not really a kind of the other, inheritance is the wrong tool; a property holding the other type often fits better.
class Shape {
var name: String
init(name: String) { self.name = name }
func label() -> String { "a \(name)" }
}
class Square: Shape {
var side = 1.0
func area() -> Double { side * side }
}
let s = Square(name: "square")
s.side = 3
print(s.label())
print(s.area())Output:
a square
9.0Challenge
EasyEmployee stores a name and a salary and has a method raise(by:) that increases the salary by a percentage (rounded down). Declare a subclass Manager that adds a stored property reports (an array of names, empty at first) and a method addReport(_:), and a method teamSize() that returns the number of reports.
The supplied code creates a manager from the first line (name,salary), adds each following name as a report, gives a 10% raise, and prints Ada earns 5500 and leads 2.
Your code goes in Employee.swift and Manager.swift. main.swift holds the supplied input/output code and cannot be edited.
Try it yourself
// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let head = input[0].split(separator: ",").map(String.init)
let boss = Manager(name: head[0], salary: Int(head[1])!)
for name in input.dropFirst() { boss.addReport(name) }
boss.raise(by: 10)
print("\(boss.name) earns \(boss.salary) and leads \(boss.teamSize())")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesMethods and selfInitializersClasses Are ReferencesRecap - Library Card4Encapsulation
Access ControlRead-Only From OutsideGuarding StateFailable InitializersRecap - Bank Account7Polymorphism and Generics
PolymorphismType CastingGeneric FunctionsGeneric TypesRecap - Shape Calculator5Inheritance
SubclassesOverriding MethodsInitializers and superfinal and HierarchiesRecap - Employee Hierarchy11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Swift playground