Swift Program to Show Use of Super Keyword in Class


In Swift, super keyword in used to access or call the methods, properties, and initialisers of the superclass from the base class. Or we can say that super keyword add more functionality to the superclass by adding its own unique behaviour. You can use super keyword with class properties, methods, and initialisers.

Example

In the following swift example, we will create a superclass or base class named as Books with bookName property, init() initialiser and display() method. Then we create a subclass named as Author, it is inherits from Author class along with override initi() initialiser and display() method. In the override initialiser and method, we use super keyword to call the super class implementation(super.display()) of the method before adding our own implementation.

import Foundation
import Glibc

// Base class
class Books{
   var bookName: String
    
   init(bookName:String){
      self.bookName = bookName
   }
   func display() {
      print("Book are the best friends")
   }
}

// Subclass
class Author:Books{
   override init(bookName:String){
    
      // Calling the super class initialiser
      super.init(bookName:bookName)
   }
   override func display(){
    
      // Calling the super class implementation
      super.display()
      print("Author name is sohan")
        
   }
}

// Creating instance of subclass
let obj = Author(bookName: "Somita")
obj.display()

Output

Book are the best friends
Author name is sohan

Conclusion

So this is how we can show use of super keyword in class. It is a very useful keyword and adds more functionality to your code by accessing the methods, and properties of super class. It is quit similar to the super keyword present in the object oriented programming like Java, Objective-C, etc.

Updated on: 24-Apr-2023

395 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements