Use the final keyword in the definition of a class to declare classes, properties, methods, and subscripts. final declared classes cannot be inherited, andfinal declared properties, methods, and subscripts cannot be overridden.
Let's look at an example:
[HTML]View PlainCopyprint?
Final class Person {//declared as final, indicating that it cannot be inherited
var name:string
Final var age:int//Defined Age property
Final func description ()-> String {//Define Description instance method
Return "\ (name) age is: \ (aged)"
}
Final class Func Printclass ()-> () {//define Printclass static method
Print ("Person prints ...")
}
Init (name:string, Age:int) {
self.name = name
self.age = Age
}
}
Class Student:person {//Compile error
var school:string
Convenience init () {
Self.init (Name: "Tony", Age:18, School: "Tsinghua University")
}
Init (name:string, Age:int, school:string) {
Self.school = School
Super.init (Name:name, Age:age)
}
Override Func Description ()-> String {//Compile error//attempt to override Description instance method
Print ("Parent class printing \ (Super.description ())")
Return "\ (name) is: \ (age), school: \ (school). "
}
Override class Func Printclass ()-> () {//Compile error//attempt to override Printclass static method
Print ("Student printing ...")
}
Override Var Age:int {//Compile error//attempt to override age property
get {
Return Super.age
}
set {
super.age = newvalue < 8? 8:newvalue
}
}
}
When you define the student class and declare it as the person subclass, the following compilation error is reported:
Inheritance from a finalclass ' person '
The definition of the Age property is final, and the following compilation error is reported when attempting to override the attribute:
var overrides a ' final ' var
Defining the Description instance method, which is declared final, the following compilation error is reported when attempting to override the description instance method:
Instance method Overridesa ' final ' Instance method
Defining the Printclass static method, which is declared final, the following compilation error is reported when attempting to override the Printclass static method:
Class method overrides a ' final ' class method
Using final can control our classes being limited inheritance, especially when developing some commercial software, it is necessary to add the final limit appropriately.
swift-final keyword-b