Home » Swift Inheritance

Swift Inheritance

by Online Tutorials Library

Inheritance in Swift

In Swift programming language, a class can inherit properties, methods and other characteristics from another class. Inheriting these properties and attributes from one class to another class is known as inheritance.

Sub class: The class which inherits the properties from other class is called child class or sub class.

Super class: The main class from where the subclass inherits the properties is known as parent class or super class.

Swift4 classes consist of superclass which calls and accesses methods, properties, functions and overriding methods. Property observers are used to add a property and modify the stored and computed property methods.

Syntax:

Base Class

A Base Class is a class which does not inherit methods, properties or functions from another class.

Example

Output:

Aryan  70  80  

Here, class with classname StudentDetails is defined as a base class which contains student’s name, and three subjects mark as mark1, mark2 and mark3. The ‘let’ keyword is used to initialize the value for the base class and base class value is displayed using ‘print’ function.

Subclass

The subclass inherits properties, methods and functions of its base class. To define a subclass ‘:’ is used before the base class name.

Example

Output:

India  Travis  Head  

Overriding

Overriding is used to access the super class instance, type methods, instance, type properties and subscripts. It uses a keyword ‘override’ to override the methods declared in the superclass.

Use of super keyword

‘super’ keyword is used as a prefix to access the methods, properties and subscripts declared in the super class.

Overriding Access to methods,properties and subscripts
Methods super.somemethod()
Properties super.someProperty()
Subscripts super[someIndex]

Next TopicSwift Methods

You may also like