Swift Introduction | Class Basics | Class Inheritance
Classes are useful because they group related functions and variables, but their most important benefit is code reuse. Once a class is available, you can use the same features wherever they are needed.
Inheritance extends class reuse. It defines a new class that receives all the features of an existing class. When a useful class already exists, you can inherit from it and add your own features.
Define an inherited class as follows.
class ClassName: SuperclassName {
... class contents ...
}
The original class is called the superclass. The new class that inherits from it is called the subclass. A subclass can use all the features of its superclass.
The following example uses inheritance.
import Cocoa
class Helo {
var name:String = "Taro";
func say(){
print("Hello, " + name + "!");
}
}
class Hello:Helo {
var name2:String = "YAMADA";
func say2(){
print("Hi," + name + "-" + name2 + "!");
}
}
var obj:Hello = Hello();
obj.say();
obj.name = "Hanako";
obj.name2 = "TANAKA";
obj.say2();
This code creates and uses the Hello class, which inherits from Helo. An instance of Hello can use the name2 property and say2 method added by Hello, as well as the name property and say method inherited from Helo.
The say2 method uses the name property defined in its superclass. Features in a superclass can be treated as features of the subclass.
Calling a Superclass Initializer
Consider another inheritance example.
class Friend {
var name:String
init(name:String) {
self.name = name
}
}
class BestFriend : Friend {
var age:Int
init(name:String, age:Int) {
self.age = age
super.init(name:name)
}
}
var you = BestFriend(name: "Taro", age: 30)
print("\(you.name) (\(you.age))")
This code defines BestFriend by inheriting from Friend. Although BestFriend does not declare a name property, it can use the property inherited from Friend.
The BestFriend initializer contains super.init(name:name). The super keyword refers to the superclass. This statement calls the initializer of Friend. Other superclass methods can also be called in the form super.methodName.