在Swift中实现继承

2021-12-24  本文已影响0人  一个栗

定义基类

class Vehicle {
    var currentSpeed = 0.0
    var description: String {
        return "traveling at \(currentSpeed) miles per hour"
    }
    func makeNoise() {
    }
}

子类

class Vehicle {
    var currentSpeed = 0.0
    var description: String {
        return "traveling at \(currentSpeed) miles per hour"
    }
    func makeNoise() {
        
    }
}

class Bicycle: Vehicle {
    var hasBasket = false
}

let bicycle = Bicycle()
bicycle.hasBasket = true
bicycle.currentSpeed = 15.0
print("Bicycle:\(bicycle.description)")

执行结果如下:
Bicycle:traveling at 15.0 miles per hour

重写

访问父类的方法、属性和下标脚本

重写方法

class Vehicle {
    var currentSpeed = 0.0
    var description: String {
        return "traveling at \(currentSpeed) miles per hour"
    }
    func makeNoise() {
        
    }
}

class Train: Vehicle {
    override func makeNoise() {
        print("呜呜~")
    }
}

let train = Train()
train.makeNoise()

重写属性的 getter 和 setter

class Vehicle {
    var currentSpeed = 0.0
    var description: String {
        return "traveling at \(currentSpeed) miles per hour"
    }
    func makeNoise() {
        
    }
}

class Car: Vehicle {
    var gear = 1
    override var description: String {
        return super.description + "in gear \(gear)"
    }
}

let car = Car()
car.currentSpeed = 25.0;
car.gear = 3
print("Cat:\(car.description)")

执行结果如下:
Cat:traveling at 25.0 miles per hourin gear 3

重写属性的观察器

class AutomaticCar : Car {
    override var currentSpeed: Double {
        didSet {
            gear = Int(currentSpeed / 10.0) + 1
        }
    }
}

let automatic = AutomaticCar()
automatic.currentSpeed = 35.0
print("AutomaticCar:\(automatic. description)")

执行结果如下:
AutomaticCar:traveling at 35.0 miles per hourin gear 4

防止重写

上一篇 下一篇

猜你喜欢

热点阅读