Inheritance and Overrides
Lesson 37 of 48 in Coddy's Swift for Java Developers course.
Both Java and Swift support single class inheritance. Java normally allows overriding non-final instance methods, with @Override checking intent. Swift requires the override keyword when a subclass overrides inherited behavior. A final class or method forbids further overriding.
The examples specialize a greeting through a superclass-typed reference. Dynamic dispatch calls the override. Swift structs do not participate in class inheritance; use protocol conformance and composition for value types. An initializer is separate from an ordinary method: subclass initialization must establish stored state and satisfy superclass initialization rules.
Java: complete program
Greeter.java
public class Greeter {
public String greeting() { return "Hi"; }
}FormalGreeter.java
public class FormalGreeter extends Greeter {
@Override public String greeting() { return "Good day"; }
}Main.java
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) throws Exception {
Greeter greeter = new FormalGreeter();
System.out.println(greeter.greeting());
}
}Swift: complete program
Greeter.swift
import Foundation
class Greeter {
func greeting() -> String { "Hi" }
}FormalGreeter.swift
import Foundation
final class FormalGreeter: Greeter {
override func greeting() -> String { "Good day" }
}main.swift
import Foundation
let greeter: Greeter = FormalGreeter()
print(greeter.greeting())Java constructors are not inherited. Swift initializer inheritance is conditional, and a subclass does not automatically gain every initializer just by naming its superclass. Do not extrapolate method overriding rules to all initializer declarations.
Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Java Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog Merge8Designing Types
Inheritance and OverridesComposition Through a PolicyAccess Control and InvariantsEnums with Associated ValuesFailable InitializationRecap: Booking LedgerPractice on your own: Swift playground