ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Swift program to call a superclass init() method from subclass

Here, we are going to learn how to call a superclass init() method from subclass in Swift programming language?
Submitted by Nidhi, on July 15, 2021

Problem Solution:

Here, we will call the superclass init() method from subclass init() method using the super keyword.

Program/Source Code:

The source code to call a superclass init() method from subclass is given below. The given program is compiled and executed successfully.

// Swift program to call a superclass init() method
// from the subclass

import Swift

class Sample1
{
    var num1:Int
    var num2:Int

    init(num1:Int,num2:Int)
    {
        self.num1 = num1
        self.num2 = num2
    }
}

class Sample2 : Sample1
{
    var num3:Int

    init(num1:Int,num2:Int,num3:Int)
    {
        self.num3 = num3
        super.init(num1:num1,num2:num2)
    }
}

var obj = Sample2(num1:10,num2:20,num3:30)

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

Output:

Num1:  10
Num2:  20
Num3:  30

...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 the init() method. The init() method is used to initialize the data members of the class. We called the init() method of Sample1 class from the init() method of subclass Sample2 using the super keyword. Then we created object obj of Sample2 class and printed the value 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.