Q:

Swift program to implement hybrid inheritance

0

Here, we will implement hybrid inheritance by combining two types of inheritances. In our case, we will combine hierarchical and multilevel inheritances.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to implement hybrid inheritance is given below. The given program is compiled and executed successfully.

// Swift program to implement hybrid inheritance

import Swift

class A {
    var numA: Int = 0

    func setA(n: Int) {
        numA = n
    }

    func printA() {
        print("numA: ", numA)
    }
}

class B : A {
    var numB: Int = 0

    func setB(n: Int) {
        numB = n
    }

    func printB() {
        print("numB: ", numB)
    }
}

class C : B {
    var numC: Int = 0

    func setC(n: Int) {
        numC = n
    }

    func printC() {
        print("numC: ", numC)
    }
}

class D : A {
    var numD: Int = 0

    func setD(n: Int) {
        numD = n
    }

    func printD() {
        print("numD: ", numD)
    }
}

var obj1 = C()
var obj2 = D()

obj1.setA(n:10)
obj1.setB(n:20)
obj1.setC(n:30)

obj1.printA()
obj1.printB()
obj1.printC()

obj2.setA(n:40)
obj2.setD(n:50)

obj2.printA()
obj2.printD()

Output:

numA:  10
numB:  20
numC:  30
numA:  40
numD:  50

...Program finished with exit code 0
Press ENTER to exit console.

Explanation:

In the above program, we imported a package Swift to use the print() function using the below statement,

import Swift

Here, we created five classes ABCDE. And, we inherited class A into B and D classes. The class B is inherited into C. Then we created the objects of the C and D classes and then set and print values on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now