Menu
CoddyTech

Inheritance and Overrides

Lesson 37 of 48 in Coddy's Swift for Dart Developers course.

Dart classes can extend a superclass and override inherited behavior; @override is an annotation that helps tools check intent. Swift requires the override keyword when replacing an inherited method. Swift classes are inheritable unless restricted by final or access rules, and structs cannot inherit from classes. Call super when the subclass wants to build on a base implementation. A base-typed reference still dispatches an overridden instance method to the actual subclass. Keep each Swift class in its own file and import Foundation separately when needed.

Complete Dart program. Each labelled block is a separate file.

Speaker.dart

class Speaker {
  String speak() => 'hello';
}

Whisper.dart

import 'Speaker.dart';
class Whisper extends Speaker {
  @override
  String speak() => '${super.speak()}...';
}

main.dart

import 'Speaker.dart';
import 'Whisper.dart';
void main() {
  final Speaker voice = Whisper();
  print(voice.speak());
}

Complete Swift program. Each labelled block is a separate file.

Speaker.swift

import Foundation
class Speaker { func speak() -> String { "hello" } }

Whisper.swift

import Foundation
final class Whisper: Speaker {
    override func speak() -> String { super.speak() + "..." }
}

main.swift

import Foundation
let voice: Speaker = Whisper()
print(voice.speak())
challenge icon

Challenge

Easy

Implement class Rate with init() and fee(units: Int) -> Int returning twice units. Implement subclass RushRate, overriding fee to add 5 to the base fee. Input is base or rush then units 0 through 100. Select an instance through a Rate reference and output its fee.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Rate.swift, RushRate.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
let r: Rate = RushRate(); return r.fee(units: 7) == 19 && Rate().fee(units: 7) == 14 && r.fee(units: 0) == 5
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Dart Developers

Practice on your own: Swift playground