What is the difference between final Class and Class?
final class A {
}
class B {
}
Other answers are already given enough understanding about final keyword. I want to explain by some example.
Consider below example without final
Keyword.
class A {
public var name: String
var breed: String
init(name: String, breed: String) {
self.name = name
self.breed = breed
}
}
class B:A{
override init(name: String, breed: String) {
super.init(name: name, breed: breed)
}
}
In above code it allow to overwrite the varible of it's super class. While Class with final keyword don't allow it. Refer below example.
final class A {
public var name: String
var breed: String
init(name: String, breed: String) {
self.name = name
self.breed = breed
}
}
class B:A{
**//ERROR:inheritance from a final class 'A' class B**
override init(name: String, breed: String) {
super.init(name: name, breed: breed)
}
}
Above code will give error inheritance from a final class A class B
Besides final
declaration does not need to be overridden also has better performance than no use final
, because final
disable dynamic dispatch at runtime which save runtime overhead.
Classes marked with final
can not be overridden.
Why should one care at all whether class can or can't be overridden?
There are two things to consider:
final
prevents class to be subclassed—mission accomplished. You can also use final
to mark methods, properties, and even subscripts of non-final classes. This will have same effect, but for particular part of the class.final
also tells Swift compiler that method should be called directly (static dispatch) rather than looking up a function from a method table (dynamic dispatch). This reduces function call overhead and gives you extra performance. You can read more on this on Swift Developer Blog.Use final when you know that a declaration does not need to be overridden. The final keyword is a restriction on a class, method, or property that indicates that the declaration cannot be overridden. This allows the compiler to safely elide dynamic dispatch indirection.
Read more:
https://developer.apple.com/swift/blog/?id=27
Final means that no one can inherit from this class.
Hoping I can boil down the other answers into this SSCCE that helped me:
open class Open {} // Anyone can see, anything can subclass
public class Normal {} // Anyone can see, internal can subclass
internal class Internal {} // Internal can see, internal can subclass
public final class Final {} // Anyone can see, nothing can subclass
In your project/module:
class SubOpen: Open {} // OK
class SubNormal: Normal {} // OK
class SubInternal: Internal {} // OK
class SubFinal: Final {} // Error: Can't subclass
In some other project/module:
class SubOpen: Open {} // OK
class SubNormal: Normal {} // Error: Can't subclass
class SubInternal: Internal {} // Error: `Internal` type not found
class SubFinal: Final {} // Error: Can't subclass