When we declare a class, we can declare it as a "child" of another class, which makes it inherit its properties, constructors and functions.
class MyParentClass {
let property: String = "MyParentClass Property"
init() {}
func method() {
print("Method")
}
}
class MyChildClass: MyParentClass {
}
let child = MyChildClass()
print(child.property) // Console shows: MyParentClass Property
child.method() // Console shows: "Method"
As you can see, when we declare MyChildClass
, we indicate that it is a subclass of MyParentClass
, which causes MyChildClass
to inherit its properties, methods, and constructors.
Practical Example
To see how this can be applied usefully, letโs imagine we need to create an APP for a hospital, and we have to manage a list of workers and patients.
If we create a Employee
class and a Patient
class, we would repeat the properties that both types of people share, such as name, age, address... However, if we create a Person
class for both, we would have many properties that one of the types wouldnโt use, such as position or room.
The best solution is to create subclasses. First, we will create the Person
class that will have only the common properties, and then, for each type, we will create a subclass with the properties that are exclusive to each one.
class Person {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
class Employee: Person {
let position: String = "Doctor" // Value assigned as an example
}
class Patient: Person {
let room: Int = 200 // Value assigned as an example
}
let patientOne = Patient(name: "Pedro", age: 45)
print(patientOne.name)
print(patientOne.room)
let employeeOne = Employee(name: "Pablo", age: 35)
print(employeeOne.name)
print(employeeOne.position)
Init in a Subclass
Since subclasses have their own properties, they need their own constructors instead of using the superclass (Person
) constructor. To do this, we need to create an init in the subclasses and call the superclass init with the necessary parameters. These constructors must also include the parameters of their superclass.
class Person {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
class Employee: Person {
let position: String
init(name: String, age: Int, position: String) {
self.position = position
super.init(name: name, age: age)
}
}
class Patient: Person {
let room: Int
init(name: String, age: Int, room: Int) {
self.room = room
super.init(name: name, age: age)
}
}
let patientOne = Patient(name: "Pedro", age: 45, room: 200)
print(patientOne.name)
print(patientOne.room)
let employeeOne = Employee(name: "Pablo", age: 35, position: "Doctor")
print(employeeOne.name)
print(employeeOne.position)
In these new init
, the value must first be assigned to the subclass properties, and then the init of the superclass is called, which will assign the rest of the values.
Be the first to comment