[swift] 부모 클래스에서 정의된 속성과 메서드를 자식 클래스에서 활용하는 방법
부모 클래스에 정의된 속성과 메서드를 자식 클래스에서 사용하려면 상속을 활용해야 합니다.
상속 구조 정의하기
class ParentClass {
var property: String
init(property: String) {
self.property = property
}
func parentMethod() {
print("This is a method in the parent class")
}
}
class ChildClass: ParentClass {
// 자식 클래스의 고유한 내용 추가 가능
}
위 코드에서 ChildClass
는 ParentClass
를 상속하여 부모 클래스에서 정의된 property
와 parentMethod()
를 사용할 수 있습니다.
부모 클래스의 메서드 오버라이드하기
class ChildClass: ParentClass {
override func parentMethod() {
super.parentMethod() // 부모 클래스의 메서드 호출
print("This is a method in the child class")
}
}
override
키워드를 사용하여 자식 클래스에서 부모 클래스의 메서드를 오버라이드할 수 있습니다.
상속되는 속성 및 메서드 활용하기
let childObject = ChildClass(property: "example")
print(childObject.property) // "example"
childObject.parentMethod() // "This is a method in the parent class"
// "This is a method in the child class"
ChildClass
인스턴스를 생성하면 상속된 속성과 메서드를 활용할 수 있습니다.
자식 클래스에서 상속받은 속성과 메서드를 활용하여 고유한 로직을 추가하고, 필요에 따라 오버라이딩하여 부모 클래스의 기능을 재정의할 수 있습니다.
참고 문헌: Apple Developer Documentation