Inheritance II
Overriding.
Inheritance II
Overriding.
0
0
Checkbox to mark video as read
Mark as read

Override a Function

As we have seen previously, a subclass will inherit all properties, functions, and init from its superclass. However, one or more subclasses may need, for example, to execute the same function but differently.

Let's imagine we have the superclass Person and subclasses Employee, Patient, and Visitor.

class Person {
    let name: String

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

    func canLeave() -> Bool {
        return true
    }
}

class Employee: Person {

}

class Patient: Person {

}

class Visitor: Person {

}

Person has the function canLeave(). This function returns a Bool value indicating whether a person can leave the hospital, which in general will be true. This function is common because both employees and visitors can leave without restrictions.

However, since a patient cannot leave, we can override that canLeave() function in the Patient subclass to return a different value. So when we call the canLeave() function, if it exists in the subclass, it will be executed; otherwise, the superclass function will be executed.

To do this, we must create the same function with the override keyword.

class Patient: Person {
    override func canLeave() -> Bool {
        return false
    }
}

Now Patient has its own canLeave() function, so when we call it using a Patient object, the result will be false, but in the case of Employee and Visitor, the result will be true, as returned by the Person class.

Override in init

class Person {
    let name: String

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

class Employee: Person {
    override init(name: String) {
        super.init(name: name)
    }
}

When overriding an init that assigns initial values as in our example, we must call the init of the superclass.

Override a Property

override can only be applied to computed variables.

class Person {
    var name: String
    var description: String {
        return "This is a person named: \(name)"
    }

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

class Employee: Person {
    override var description: String {
        return "This is a employee named: \(name)"
    }
}

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy