Inheritance in Swift
Inception in Programming Language
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,
- Base Class
- Sub Class
- Overriding
- Preventing Overriding
1. Base Class
Any class that does not inherit from another class is known as a base class.
Syntax
class ClassName {
//Declaration of properties and methods
}
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
class SubClassName: BaseClassName {
//Sub Class Declaration
}
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
class SubClassName: BaseClassName {
override var or func
}
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
class ClassName {
final var: Type
}
Example
Preventing Method Override
This prevents the method from being overridden
Syntax
class ClassName {
final func functionName() {
//Function Definition
}
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
final class ClassName {
//Class Declaration
}
Example
So far concepts on the base class, subclass, overriding, and preventing overriding are covered.