Swift, Inheritance 상속

Swift의 클래스 상속은 클래스의 속성과 방법, 또는 다른 특성을 상속할 수 있습니다.하위 클래스도 부모 클래스를 다시 쓰는 방법이나 속성을 사용할 수 있습니다.
상위 클래스를 정의합니다.
class Vehicle {
    var currentSpeed = 0.0;
    var description:String{
        return "traverling at \(currentSpeed) miles per hour"
    }
    func makeNoise(){
        
    }
}
///  Vehicle  
let somevehicle = Vehicle()
somevehicle.currentSpeed = 5;
print("Vehicle:\(somevehicle.description)")
// Vehicle:traverling at 5.0 miles per hour
1.하위 클래스 만들기
///     Vehicle
class Bicycle: Vehicle {
    var hasBasket = false
}
let bicycle = Bicycle();
bicycle.hasBasket = true
bicycle.currentSpeed = 15;
print("Bicycle:\(bicycle.description)")
// Bicycle:traverling at 15.0 miles per hour
2.Bicycle에서 상속되는 하위 클래스 만들기
///     Bicycle
class Tandem: Bicycle {
    var currentNumberOfPassengers = 0
}
let tandem = Tandem()
tandem.hasBasket = true
tandem.currentNumberOfPassengers = 2
tandem.currentSpeed = 22.0
print("Tandem: \(tandem.description)")
// Tandem: traverling at 22.0 miles per hour
3.다시 쓰다
Overriding
3.1 부류를 다시 쓰는 방법
다시 쓰기 속성
4
//  
class Train: Vehicle {
    override func makeNoise() {
        print("Choo Choo")
    }
}
let train = Train()
train.makeNoise()
// Choo Choo
3 다시 쓰기 속성 모니터
//  
class SpeedLimitedCar: Vehicle {
    override var currentSpeed: Double  {
        get {
            return super.currentSpeed
        }
        set {
            super.currentSpeed = min(newValue, 40.0)
        }
    }
}
let limitedCar = SpeedLimitedCar()
limitedCar.currentSpeed = 60.0
print("SpeedLimitedCar: \(limitedCar.description)")
// SpeedLimitedCar: traverling at 40.0 miles per hour
4.재작성 방지
다시 쓰는 것을 방지하려면 속성, 방법, 클래스, 앞에 키워드final을 붙여야 합니다.
You can prevent a method, property, or subscript from being overridden by marking it as final. Do this by writing the  final  modifier before the method, property, or subscript’s introducer keyword (such as  final varfinal funcfinal class func , and  final subscript ).
Any attempt to override a final method, property, or subscript in a subclass is reported as a compile-time error. Methods, properties, or subscripts that you add to a class in an extension can also be marked as final within the extension’s definition.
You can mark an entire class as final by writing the  final  modifier before the  class  keyword in its class definition ( final class ). Any attempt to subclass a final class is reported as a compile-time error.

좋은 웹페이지 즐겨찾기