Swift 继承 v.s 调用 super
Swift Inheritance v.s calling super
我正在学习 Swift 编程语言中的以下章节:
If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
然后我在我的目标中尝试了这些代码:
class Car {
var name: String = "Unknown"
init(name: String) {
self.name = name
}
}
class RacingCar: Car {
var speed = 0.0
init(name: String, speed: Double) {
self.speed = speed
super.init(name: name)//this is where I got confused
}
}
根据规则一,RacingCar class 不会从它的 superclass Car 继承 init(name:) 指定的初始化器。但是,我仍然可以在我的 subclass 中调用 super.init(name:)。怎么会这样?我对此很困惑。谁能解释为什么?谢谢
继承初始化器意味着该初始化器可用于您的 子类 的实例(这就是继承的含义);也就是说,您的子类的初始化程序可以在 self
:
上调用它
class RacingCar: Car {
var speed = 0.0
init(name: String, speed: Double) {
self.speed = speed
self.init(name: name) // <-- Error: This initializer is not inherited
}
}
您无需继承构造器即可在 super
上调用它:超类不会因为您对其进行子类化而失去对其构造器的访问权限。
class RacingCar: Car {
var speed = 0.0
init(name: String, speed: Double) {
self.speed = speed
super.init(name: name) // <-- Works: super class does have this initializer
}
}
我正在学习 Swift 编程语言中的以下章节:
If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
然后我在我的目标中尝试了这些代码:
class Car {
var name: String = "Unknown"
init(name: String) {
self.name = name
}
}
class RacingCar: Car {
var speed = 0.0
init(name: String, speed: Double) {
self.speed = speed
super.init(name: name)//this is where I got confused
}
}
根据规则一,RacingCar class 不会从它的 superclass Car 继承 init(name:) 指定的初始化器。但是,我仍然可以在我的 subclass 中调用 super.init(name:)。怎么会这样?我对此很困惑。谁能解释为什么?谢谢
继承初始化器意味着该初始化器可用于您的 子类 的实例(这就是继承的含义);也就是说,您的子类的初始化程序可以在 self
:
class RacingCar: Car {
var speed = 0.0
init(name: String, speed: Double) {
self.speed = speed
self.init(name: name) // <-- Error: This initializer is not inherited
}
}
您无需继承构造器即可在 super
上调用它:超类不会因为您对其进行子类化而失去对其构造器的访问权限。
class RacingCar: Car {
var speed = 0.0
init(name: String, speed: Double) {
self.speed = speed
super.init(name: name) // <-- Works: super class does have this initializer
}
}