ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.