Swift - Custom Type Preventing Subclassing

Introduction

To prevent a class from being inherited, use final keyword.

Consider the following Square class:

class Rectangle: Shape {
       //override the init() initializer
       override init() {
           super.init()
       }

       //overload the init() initializer
       init(length:Double, width:Double) {
           super.init()
           self.length = length
           self.width = width
       }

     //override the area() function
     final override func area() -> Double {
         return self.length * self.width
     }
}
final class Square: Rectangle {
       //overload the init() initializer
       init(length:Double) {
           super.init()
        self.length = length
        self.width = self.length                                                                  
    }
}

The Square class inherits from the Rectangle class and the class definition is prefixed with the final keyword.

No one other class can inherit from Square class.

For example, the following is not allowed:


//cannot inherit from Square as it is final
class rhombus: Square {
 
}

Because the area() method has been declared to be final in the Rectangle class, the Square class is not allowed to override it, as shown here:

final class Square: Rectangle {
    //overload the init() initializer
    init(length:Double) {
        super.init()
        self.length = length
        self.width = self.length
    }

     //cannot override a final method
     //override the area() function
     override func area() -> Double {
          ...
     }

}

Related Topic