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
keyword is only necessary if the function exists in the superclass. The function must have the same name, the same parameters, and return the same type; otherwise, it will be considered a different function and will not override the superclass function. The same applies to properties and inits.
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
keyword "replaces" the element from the superclass, so that code won't be executed unless we explicitly call it.
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)"
}
}
Be the first to comment