본문 바로가기
수업내용

20230807 Kotlin Constructor

by titlejjk 2023. 8. 7.
package com.example.hellokotlin

class Human{
    val name:String
    //String type을 전달 받는 생성자
    constructor(name:String){
        this.name=name
    }
}

fun main(){
    val h1=Human("뉴진스")
}

위와 같이 class에서 지정한 type을 생성자의 인자로 전달을 해주어야지 오류가 발생하지 않는다.

class Human2 constructor(name:String){
    val name:String
    init {
        this.name=name
    }
}

위의 Human1 Class를 Human2 Class와 같은 형태로도 정의 할 수 있다.

 

이를 더 줄이면 아래와 같이 코드를 작성할 수 있다.

class Human3 constructor(val name:String){
   
}

여기서 더 줄인다면 아래와같다.

//위의 작업을 조금 더 줄여서 쓰면 아래와 같다.
class Human4(val name:String)

constructor는 생략이 가능하기 때문이다.

 

참조값을 출력했을 때 필드안에 들어 있는 내용을 확인 가능하게 해서 개발을 용이하게 하려면 data키워드를 이용해서 Class를 정의하면 된다.

//참조값을 출력했을 때 필드안에 들어 있는 내용을 확인 가능하게 해서 개발을 용이하게 하려면
data class Human5(val name:String)//data키워드를 이용해 클래스를 정의하면 된다.

 

 

용도에 따라서 다양한 생성자 호출도 가능하다.

package com.example.hellokotlin

class MyData{
    //3가지 종류의 생성자
    constructor(){
        println("()생성자 호출")
    }
    constructor(num:Int)
    constructor(num:Int, name: String)
}

fun main(){
    val d1=MyData()
    val d2=MyData(1)
    val d3=MyData(1,"뉴진스")
}

생성자가 오버로딩되어 있다.

'수업내용' 카테고리의 다른 글

20230803 Kotlin  (0) 2023.08.03
20230801 Kotlin  (0) 2023.08.01
20230731 Kotlin  (0) 2023.08.01
20230731 Kotlin  (0) 2023.07.31
20230728 Kotlin  (0) 2023.07.28

댓글