swift基础之类继承

原创
2021/04/16 09:24
阅读数 0

基类

//基类
class Vehicle {
    var currentSpeed = 0.0
    
    var description: String {
        return "traveling at \(currentSpeed) miles per hour"
    }
    
    func makeNoise() {
        
    }
    
    //阻止重写final
    final func stop() {
        print("stoped")
    }
}

继承

//继承
class Bicycle : Vehicle {
    var hasBasket = false
}

方法重写 override

class Train: Vehicle {
    //方法重写
    override func makeNoise() {
        print("hu wu! hu wu!")
    }
}

属性重写 override

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

let bicycle = Bicycle()
bicycle.hasBasket = true
bicycle.currentSpeed = 15.0
print(bicycle.description)
//traveling at 15.0 miles per hour

let train = Train()
train.makeNoise()
//hu wu! hu wu!

let car = Car()
print(car.description)
//traveling at 0.0 miles per hour in gear 1
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部