Inheritance in Swift

Inception in Programming Language

Dhayaalan Raju
IVYMobility TechBytes
2 min readMay 27, 2020

--

What is Inheritance?

Inheritance allows a class to have the same behavior as of another class and extend that behavior to provide specific needs.

Why Inheritance?

One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common code amongst several subclasses.

When one class inherits from another, the inheriting class is known as a subclass, and the class it inherits from is known as its base class.

Inheritance is a fundamental behavior that differentiates classes from other types in Swift.

Topics Covered are,

  1. Base Class
  2. Sub Class
  3. Overriding
  4. Preventing Overriding

1. Base Class

Any class that does not inherit from another class is known as a base class.

Syntax

Example

2. Sub Class

The subclass inherits characteristics(i.e. Methods and Properties) from the existing class. New characteristics can also be added to the subclass.

Syntax

Example

An important concept in the subclass is overriding. Let's get into that.

3. Overriding

To provide an own custom implementation in a subclass overriding is used.

Overriding is something changing or adding the functionality which is derived from the base class without changing its signature(without changing the method name and the parameter list).

Syntax

Example

  • In the above example, the Manager class is inherited from the Employee class.
  • The manager class adds an extra variable called the bonus.
  • Then the base class initializer of Employee is called from the Manager class.
  • Then base class method printDetails is called from the Manager class printDetails method.
  • Finally, Also the base class variables firstName and lastName are called from the method.

4. Preventing Override

A method or property can be prevented from being overridden by marking it as final.

Any attempt to override a final method or a property in subclass results in a compile-time error.

Not only the method or property even a class can be marked as final.

Any attempt to inherit the final class results in a compile-time error.

Preventing Property Override

This prevents the property from being overridden.

Syntax

Example

Preventing Method Override

This prevents the method from being overridden

Syntax

Example

Preventing Class Override

For methods and properties, the final keyword doesn't allow them to be overridden. In the case of a class it prevents it from being extended.

Syntax

Example

So far concepts on the base class, subclass, overriding, and preventing overriding are covered.

--

--