Codebender
Codebender

Reputation: 14471

Marking an open method final in subclass

Consider the following example:

open class A { // This class is from the SDK and cannot be modified in anyway.
    open func aFunc() {}
}

This below is my own class and I need the class to be open for others to override. But the method should NOT be available for overriding.

open class B : A { // This has to be open for others to override.
    override open func aFunc() {} // I need to make this **final** somehow so the subclasses cannot override this.
}

Is it possible to mark the aFunc() method in class B final?

I tried adding final keyword, but there's a compiler error saying

Instance method cannot be declared both 'final' and 'open'

If I remove the open keyword, there's a compiler error saying

Overriding instance method must be as accessible as the declaration it overrides

Upvotes: 0

Views: 195

Answers (1)

Mukesh
Mukesh

Reputation: 2902

You can do this by making the method public like this:

open class A { // This class is from the SDK and cannot be modified in anyway.
    open func aFunc() {}
}

open class B : A { // This has to be open for others to override.
    override final public func aFunc() {}
}

open keyword is for letting subclasses from different module to override, whereas the public keyword only gives access to different module and do not allow the overriding. If you want to override this method in only your module and not in other modules you can just make it public without final.

Upvotes: 3

Related Questions