Home »
Swift »
Swift Programs
Swift program to implement hierarchical inheritance
Here, we are going to learn how to implement hierarchical inheritance in Swift programming language?
Submitted by Nidhi, on July 14, 2021
Problem Solution:
Here, we will create three classes Person, Employee, and Student with data members. Then we will inherit the Person class to Employee and Student classes to implement hierarchical inheritance.
Program/Source Code:
The source code to implement hierarchical inheritance is given below. The given program is compiled and executed successfully.
// Swift program to implement hierarchical inheritance
import Swift
class Person {
var name: String = ""
var age: Int = 0
func setPerson(name: String, age: Int) {
self.name = name
self.age = age
}
func printPerson() {
print("\tName: ", name)
print("\tAge : ", age)
}
}
class Employee : Person {
var empId: Int = 0
func setEmp(id: Int, name: String, age: Int) {
empId = id
setPerson(name:name, age:age)
}
func printEmp() {
print("\tEmployee Id : ", empId)
printPerson()
}
}
class Student : Person {
var stuId: Int = 0
var fees: Float = 0
func setStudent(id: Int, name: String, age: Int, fee: Float) {
stuId = id
fees = fee
setPerson(name:name, age:age)
}
func printStudent() {
print("\tStudent Id: ", stuId)
printPerson()
print("\tFees: ", fees)
}
}
var emp = Employee()
var stu = Student()
emp.setEmp(id:101, name:"Arun", age:23)
stu.setStudent(id:1001, name:"Amit", age:15,fee:25000.56)
print("Employee Information:")
emp.printEmp()
print("Student Information:")
stu.printStudent()
Output:
Employee Information:
Employee Id : 101
Name: Arun
Age : 23
Student Information:
Student Id: 1001
Name: Amit
Age : 15
Fees: 25000.56
...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 three classes Person, Employee and Student.
The "Person" class contains data member "Name" and "Age". The "Employee" class contains a data member's "empId. The Student class contains two data members stuId and fees.
All classes contain methods to set and print data members. Then we inherited the Person class into Employee and Student classes. After that, we created the objects of Employee and Student classes and set and print information on the console screen.
Swift Inheritance Programs »