Swift program to implement property overriding

Here, we are going to learn how to implement property overriding in Swift programming language?
Submitted by Nidhi, on July 15, 2021

Problem Solution:

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.

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.

Swift Inheritance Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.