Swift 重写方法和属性
在本教程中,我们将通过实例了解 Swift中 的属性和方法重写。
在 Swift 继承 中,子类继承超类的方法和属性。在 Swift 中支持子类直接访问超类成员。
现在,如果在超类和子类中都定义了相同的方法,那么子类的方法将覆盖超类的方法。这称为重写。
我们使用 override 关键字声明方法重写。例如,
class Vehicle {func displayInfo(){...}}class Car: Vehicle {// override methodoverride func displayInfo() {...}}
这里,Car 子类的 displayInfo() 方法覆盖了 Vehicle 超类的相同方法。
实例:方法重写
class Vehicle {// method in the superclassfunc displayInfo() {print("Four Wheeler or Two Wheeler")}}// Car inherits Vehicleclass Car: Vehicle {// overriding the displayInfo() methodoverride func displayInfo() {print("Four Wheeler")}}// create an object of the subclassvar car1 = Car()// call the displayInfo() methodcar1.displayInfo()
结果为:
Four Wheeler
在上面的例子中,我们在子类 Car 中覆盖了超类 Vehicle 的 displayInfo() 方法。
// inside the Car classoverride func displayInfo() {print("Four Wheeler")}
这里,我们使用 override 关键字来指定重写方法。
现在,当我们使用 Car 的对象 car1 调用 displayInfo() 方法时,
car1.displayInfo()
子类内的方法被调用。

这是因为 Car 子类的 displayInfo() 方法覆盖了 Vehicle 超类的相同方法。
Swift 中访问重写方法
要从子类访问超类的方法,我们使用 super 关键字。例如,
class Vehicle {// method in the superclassfunc displayInfo() {print("Vehicle: Four Wheeler or Two Wheeler")}}// Car inherits Vehicleclass Car: Vehicle {// overriding the displayInfo() methodoverride func displayInfo() {// access displayInfo() of superclasssuper.displayInfo()print("Car: Four Wheeler")}}// create an object of the subclassvar car1 = Car()// call the displayInfo() methodcar1.displayInfo()
结果如下:
Vehicle: Four Wheeler or Two WheelerCar: Four Wheeler
在上面的例子中,Car 子类的 displayInfo() 方法覆盖了 Vehicle 超类的相同方法。
在 Car 的 displayInfo() 中,我们使用了,
// call method of superclasssuper.displayInfo()
调用 Vehicle 的 displayInfo() 方法。
因此,当我们使用 car1 对象调用 displayInfo() 方法时,
// call the displayInfo() methodcar1.displayInfo()
将执行 displayInfo() 方法的重写版本和超类版本。
防止方法重写
在 Swift 中,我们可以防止方法重写。
为了使方法不可重写,我们在超类中声明方法时使用 final 关键字。例如,
class Vehicle {// prevent overridingfinal func displayInfo() {print("Four Wheeler or Two Wheeler")}}// Car inherits Vehicleclass Car: Vehicle {// attempt to overrideoverride func displayInfo() {print("Four Wheeler")}}// create an object of the subclassvar car1 = Car()// call the displayInfo() methodcar1.displayInfo()
在上面的例子中,我们将超类中的 displayInfo() 方法标记为 final。
一旦方法声明为 final,我们就不能重写它。所以当我们试图覆盖 final 方法时,
override func displayInfo() {print("Four Wheeler")}
将产生错误: error: instance method overrides a ‘final’ instance method
Swift 重写属性
在 Swift 中,我们可以重写 计算属性。例如,
class University {// computed propertyvar cost: Int {return 5000}}class Fee: University {// override computed propertyoverride var cost: Int {return 10000}}var amount = Fee()// access fee propertyprint("New Fee:", amount.cost)
结果如下:
New Fee: 10000
在上面的例子中,我们在超类 University 中创建了一个计算属性。注意子类 Fee 中的代码,
override var cost: Int {return 10000}
我们正在重写计算属性 cost。现在,当我们使用目标金额 Fee 访问 cost 属性时,
// access fee propertyamount.cost
子类内的属性被调用。
class A {// stored propertyvar num = 0}class B: A {// overriding stored propertyoverride var num = 2 // Error Code}