Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call super method?

class Subclass : Superclass {
    override func method() { /* ... */ }
}

let instance = Subclass()
instance.method() // I want to call Superclass.method() not Subclass.method()

Given this scenario how can I call Superclass.method() ?

like image 591
andrewz Avatar asked Jun 06 '18 14:06

andrewz


1 Answers

You can't. When you use the override keyword you tell the compiler to allow changing an inherited method in your subclass. This means that the subclass instances will have no knowledge about the implementation of the overriden superclass method.

Even if you cast a Subclass instance to Superclass, the actual type of the instance will still be Subclass, so if you do (instance as Superclass).method() it will still execute the overriden method.

If you want to be able to call the superclass implementation from your Subclass instances, you'll need to create another function for Subclass rather than overriding method from Superclass.

like image 179
Dávid Pásztor Avatar answered Oct 18 '22 02:10

Dávid Pásztor