Object Oriented Programming

Inheritance in Swift

Inheritance is used to inherit another class' members, including fields and methods. A subclass extends a base class' members.


Syntax
modifier class subClass: baseClass {
    //the initializer is NOT inherited by default
    override init() {
        super.init()
    }

    //to access a superClass member
    super.methodName();

    //to override a superClass member, use the override keyword
    override superClassMember() {
    }
} ;

Notes

The super keyword is used to access the super class' member.

When a method is overridden, the compiler checks to see if the same method declaration exists in the super class. Override can be prevented using the 'final' keyword.


Example
public class Cat {
    var name: String    
    init() {
        this.name = "Garfield";        
    }    
    func sound() -> String { //implemented sound method from the interface
        return "Meow!";
    }
} 

public class Tiger: Cat { //the variable 'name' and the method 'sound()' are inherited
    init() {
        super.init(); //calling the constructor in the super class, Cat
    }

    override func sound() -> String { //overriding the sound() method in Cat
        return "Roar!";
    } 

    func catSound() -> String {
        return super.sound(); //calling the sound method from Cat, non-overwritten
    }
}

< Getters and Setters   |   Print >

© 2019 SyntaxDB. All Rights Reserved.