Q:

Swift program to implement property overriding

belongs to collection: Swift Inheritance Programs

0

Here, we will implement property overriding using the override keyword. Property overriding is used to implement the property with the same name in the subclass.

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 property overriding is given below. The given program is compiled and executed successfully.

// Swift program to implement property overriding

import Swift

class Sample1
{
    var num1 = 5

    var Value:Int{
        get{
            return num1
        }
        set(newValue){
            num1 = newValue
        }
    }
}

class Sample2 : Sample1
{
    var num2 = 0

    override var Value:Int{
        get{
            return num2
        }
        set(newValue){
            num2 = newValue
        }
    }
}

var obj = Sample2()

obj.Value = 10

print("Num1: ",obj.num1)
print("Num2: ",obj.num2)

Output:

Num1:  5
Num2:  10

...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 two classes Sample1 and Sample2. Both classes contain Value property. In our program, we inherited the Sample1 class into Sample2 and override the Value property using the override keyword. After that, we created the object of the Sample2 class and set the value of the num2 variable using the Value property, and print the values of data members on the console screen.

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

total answers (1)

<< Swift program to call a superclass init() method f...