Swift Introduction | Class Basics | Method Overrides

Inheritance lets you add new features to an existing class. Sometimes, however, you also need to change an inherited feature.

An override redefines a method from a superclass. Write the method definition as follows.

override func methodName() {...}

Adding override replaces the superclass implementation with the newly defined method. Calls to that method then use the new behavior.

When overriding a method, the name, arguments, and return value must match the superclass method exactly.

The following example uses an override.

import Cocoa

class Helo {
    var name:String = "Taro";

    func say(){
        print("Hello, " + name + "!");
    }
}

class Hello:Helo {
    var name2:String = "YAMADA";

    override func say(){
        print("Hi," + name + "-" + name2 + "!");
    }
}

var obj:Hello = Hello();
obj.say();

obj.name = "Hanako";
obj.name2 = "TANAKA";
obj.say();

This example changes the previous code by overriding say. Calling say on an instance of Hello invokes the implementation in Hello instead of the one in Helo.

Override Details

Inheritance lets a subclass use superclass properties and methods as they are. An override is used when a subclass needs to change an inherited feature.

Suppose a superclass defines a method named A. Calling A from a subclass normally runs the superclass method because the subclass inherits it. If the subclass overrides A, calling A runs the subclass implementation instead.

An overriding method begins with the override modifier. Its name, arguments, and return value must all match. If any of them differ, Swift treats it as a different method rather than an override.

The following example overrides printData.

class Friend {
    var name:String

    init(name:String) {
        self.name = name
    }

    func printData() {
        print("\(self.name)")
    }
}

class BestFriend : Friend {
    var age:Int

    init(name:String, age:Int) {
        self.age = age
        super.init(name:name)
    }

    override func printData() {
        print("\(self.name) (\(self.age))")
    }
}

var you = BestFriend(name: "Taro", age: 30)
you.printData()