Swift, Inheritance 상속
2802 단어 물려받다inheritance
상위 클래스를 정의합니다.
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 var
, final func
, final 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.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
상속 후의 집행 순서텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.