swift initializer

//Swift
//부모의 생성자는 자식에게 모두 상속되지 않는 것을 원칙으로 함
class Super {
    var text: String
    var extend: String
    var only: String
    
    init() {
        self.text = ""
        self.extend = ""
        self.only = ""
    }
    
    init(text: String) {
        self.text = text
        self.extend = ""
        self.only = ""
    }
    
    //required 생성자는 상속받은 자식에서 반드시 다시 구현해야 함
    required init?(extend: String) {
        print("init with super extend")
        self.text = ""
        self.extend = extend
        self.only = ""
    }
    
    //convenience 생성자는 다른 생성자 호출을 도와줌
    //convenience 생성자는 반드시 다른 생성자를 호출해야 함
    convenience init?(only: String) {
        print("init with only")
        self.init(text: "")
        self.only = only
    }
    
    deinit {
    }
}

class Sub1: Super {
    var content: String = ""
    //재정의한 생성자가 하나도 없으면 부모의 모든 생성자 상속 받음
}

class Sub2: Super {
    var content: String

    override init(text: String) {
        content = ""
        super.init(text: text)
    }
    
    //부모의 required 생성자는 반드시 구현해야 함
    required init?(extend: String) {
        print("init with sub extend")
        content = ""
        super.init(extend: extend)
    }
    
    //부모의 모든 designated 생성자를 구현하면 부모의 모든 convenience 생성자를 상속 받음
    //지금은 부모의 init()를 재정의하지 않았기 때문에 convenience 생성자를 상속 받지 않음
}
_ = Sub1(only: "only")
_ = Sub2(extend: "extend")
_ = Sub2(only: "only")  //error, Sub2에서 부모의 init()를 재정의하면 호출가능

다시 정리하면…

부모의 생성자는 자식에게 모두 상속되지 않는 것을 원칙으로 함
하지만 부모의 생성자가 자식에게 상속되는 원칙)
1. 자식에서 재정의한 생성자가 하나도 없으면 부모의 모든 생성자를 자동으로 상속 받음
2. 자식에서 designated 생생자를 모두 재정의하면 모든 convenience 생성자는 상속 받음

designated : 일반적으로 구현한 생성자
required : 자식에서 반드시 구현해야 함, required 키워드가 override 의미를 포함
convenience : 다른 생성자의 호출을 쉽게 하기 위함, 내부에서 반드시 다른 생성자를 호출해야 함

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다