코틀린 객체지향-2(보조 생성자)

Bang!·2022년 1월 13일
0

Android(코틀린)

목록 보기
3/15
post-thumbnail


보조 생성자

  • 보조 생성자는 클래스의 본문에 constructor 키워드로 선언하는 함수이다

예시)
//보조 생성자 선언
class ConstructorLearn{
constructor(name: String){
println("contructor(name: String) call..")
}
constructor(name: String, count: Int){
println("contructor(name: String, count: Int) call..")
}
}

fun main() {
    val user1 = ConstructorLearn("Stef1")
    val user2 = ConstructorLearn("stef2",10)
}

보조 생성자에 주 생성자 연결

  • 코틀린의 생성자는 주 생서자와 보조 생성자로 나눈다

  • 만약 주 생성자와 보조 생성자 모두 선언한다면 반드시 생성자끼리 연결해 주어야 한다
    ▪ 예) 주 생성자와 보조 생성자 선언하고 연결 없으면….
    class User(name: String){
    constructor(name: String){ //=> 오류!! 반드시 주랑 보조 사용하면 연결해야함!
    .....

  • 연결한 예시)
    class bothConstructor(name: String) {
    constructor(name: String, count: Int):this(name) {
    println("bothConstructor(name: String) and constructor(name: String, count: Int):this(name)....")
    }
    }

  • 보조 생성자 선언부에 this(name)만 추가한 코드이다!
    ▪ 이렇게 하면 보조 생성자와 함께 호출된다!

  • 반드시 어떤 식으로도 주 생성자가 호출되게 해야한다

  • 만약 주 생성자가 있고 보조 생성자가 여러 개 선언하면….
    ▪ 어떻게든 주 생성자가 호출되게 해야 한다

profile
pro한 프로그래머가 되자!

0개의 댓글