Swift: Inheritance

This entry is part 17 of 41 in the series Swift

Here we set up a parent class called Music and its inherited class called Rock.  Notice how we need to use super.init to initialise the 2 inherited members from the parent Music class.

import UIKit

class Music {
    
    var totalAlbums: Int
    var price: Double
    
    init(tAlb: Int, pMusic: Double) {
        self.totalAlbums = tAlb
        self.price = pMusic
    }
}

class Rock : Music{
    
    var numRock: Int
    var rockPrice: Double
    
    init(totalAlbums: Int, price: Double, nRock: Int, rPrice: Double) {
        
        self.numRock = nRock
        self.rockPrice = rPrice
    
        super.init(tAlb : totalAlbums, pMusic : price)
    }

}

var mAlbums = 1000
var mPrice = 12.50

let musicGenre = Music(tAlb: mAlbums, pMusic: mPrice)

print(musicGenre.totalAlbums)
print(musicGenre.price)
print("")

var rAlbums = 300
var rPrice = 15.60

let rockGenre = Rock(totalAlbums: mAlbums, price: mPrice, nRock: rAlbums, rPrice: rPrice)

//Now we can access the 2 members in its parent class
print(rockGenre.totalAlbums)
print(rockGenre.price)
print("")

print(rockGenre.numRock)
print(rockGenre.rockPrice)

swift

Series Navigation<< Swift editor from IBM
Swift: Getting the average >>

Leave a comment

Leave a Reply