The source code to overload the init() method is given below. The given program is compiled and executed successfully.
// Swift program to overload init() method
import Swift
class Sample {
var val1:Int
var val2:Int
init()
{
val1 = 10
val2 = 20
}
init(val1:Int, val2:Int)
{
self.val1 = val1
self.val2 = val2
}
}
var sam1 = Sample()
var sam2 = Sample(val1:30,val2:40)
print("Sam1:")
print("\tVal1: ",sam1.val1)
print("\tVal2: ",sam1.val2)
print("Sam2:")
print("\tVal1: ",sam2.val1)
print("\tVal2: ",sam2.val2)
Output:
Sam1:
Val1: 10
Val2: 20
Sam2:
Val1: 30
Val2: 40
...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 a class Sample that contains two data members val1, val2. And, we implemented two init() methods with a different number of arguments. Then we created two objects sam1 and sam2 and initialized the data members. After that, we printed the value of data members of both objects on the console screen.
Program/Source Code:
The source code to overload the init() method is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we imported a package Swift to use the print() function using the below statement,
Here, we created a class Sample that contains two data members val1, val2. And, we implemented two init() methods with a different number of arguments. Then we created two objects sam1 and sam2 and initialized the data members. After that, we printed the value of data members of both objects on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer