티스토리 뷰
Swift 또한 JAVA 나 C++과 동일하게 객체 지향 언어이기 때문에 부모 클래스의 성질을 자식 클래스에게 고스란히 상속할 수 있다.
바로 한번 알아보자.
1. 기반 클래스 정의
다른 어떤 클래스로 부터 어떤 것도 상속받지 않는 클래스를 기반 클래스라고 한다. JAVA에서는 모든 클래스가 Object 클래스를 상속하지만, swift 는 아무런 클래스도 상속받지 않는 기반 클래스를 가질 수 있다.
우선 Vehicle 이라는 기반 클래스를 하나 정의해보자. 이는 currentSpeed를 프로퍼티로, description을 계산된 프로퍼티로 가지고 있으며 makeNoise() 라는 메서드도 하나 가지고 있도록 한다.
class Vehicle {
var currentSpeed = 0.0
var description: String {
return "traveling as \(currentSpeed) miles per hour"
}
func makeNoise() {
// do nothing
}
}
2. 서브클래싱(상속)
부모 클래스를 서브 클래싱하여 이를 상속받는 새 클래스를 선언하는 코드는 아래와 같다.
class SomeSubclass: SomeSuperclass {
// subclass definition goes here
}
위 Vehicle 클래스를 상속받는 Bicycle 이라는 클래스를 선언한 뒤, 자식 클래스만의 프로퍼티를 하나 정의해주자.
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 Tandem: Bicycle {
var currentNumberOfPassengers = 0
}
let tandem = Tandem()
tandem.hasBasket = true
tandem.currentNumberOfPassengers = 2
tandem.currentSpeed = 22.0
print("Tandem: \(tandem.description)")
// Tandem: traveling at 22.0 miles per hour
3. 오버라이딩
부모클래스의 인스턴스 메소드, 타입 메소드, 인스턴스 프로퍼티, 타입 프로퍼티, 서브스크립트 모두를 재정의하여 사용할 수 있도록 오버라이드 기능을 제공한다.
이는 아래와 같이 override 키워드를 사용하여 구성할 수 있다.
- 메서드 오버라이드
class Train: Vehicle {
override func makeNoise() {
print("Choo Choo")
}
}
let train = Train()
train.makeNoise()
// Prints "Choo Choo" : 새로 정의한 내용이 출력됩니다.
- 프로퍼티 오버라이드
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("Car: \(car.description)")
// Car: traveling at 25.0 miles per hour in 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 hour in gear 4
4. 오버라이드 방지
서브클래스에서 특정 메서드, 프로퍼티, 서브스크립트가 오버라이드 되는 것을 방지하려면 final 키워드를 사용한다.
'Mobile > ios' 카테고리의 다른 글
[ios] swift 기본 문법 정리 14: DeInitialization (0) | 2022.12.07 |
---|---|
[ios] swift 기본 문법 정리 13: Initialization (0) | 2022.12.07 |
[ios] swift 기본 문법 정리 11: Subscripts (0) | 2022.12.01 |
[ios] swift 기본 문법 정리 10: Method (0) | 2022.11.30 |
[ios] swift 기본 문법 정리 9: Properties (0) | 2022.11.30 |
- 이탈리안 레스토랑
- 파니노구스토
- javascript
- redux-thunk
- AsyncStorage
- 인천 구월동 이탈리안 맛집
- redux
- 정보보안기사 #실기 #정리
- react-native
- 맛집
- await
- Promise
- Async
- 인천 구월동 맛집
- react
- Total
- Today
- Yesterday