기록하는 개발자

Kotlin(코틀린)(Intelli J) #7 Class 본문

Kotlin

Kotlin(코틀린)(Intelli J) #7 Class

밍맹030 2020. 2. 18. 22:54
728x90

Class

-객체를 생성하기 위해서는 반드시 클래스를 통해 생성 해야한다.

-클래스에서 정의한 변수(property)와 함수(method)의 구조에 따라 객체가 생성된다.

-class 키워드로 선언한다.

 

구성

-init 블록과 constructor(생성자)

-property(변수)

-method(함수)

-중첩 클래스 및 내부 클래스

-객체 선언

 

Property 특징

-java의 field와 유사한 성질을 가진다.

-PropertyType, Property_initializer, getter, setter를 가진다.

(단, var로 선언된 property는 getter만 가짐->java의 private 처럼 수정x)

 

lateinit

-선언과 통시에 초기화 하기 힘들 때 사용하는 키워드

-var로 선언 시 사용 가능

728x90

ex)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class body(val height : Int , val weight : Int)
class myclassbody{
    lateinit var num1 : body
    lateinit var num2 : body
    lateinit var num3 : body
 
    val ave_h: Int get()=(num1.height+num2.height+num3.height)/3
    val ave_w: Int get()=(num1.weight+num2.weight+num3.weight)/3
}
fun main(args : Array<String>){
    val BODY=myclassbody()
    BODY.num1=body(160,60)
    BODY.num2=body(174,70)
    BODY.num3=body(165,65)
    println("average height of this class : ${BODY.ave_h}")
    println("average weight of this class : ${BODY.ave_w}")
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

Constructor(생성자)

-초기화에 사용되며 클래스를 통해 객체를 생성할 때 자동으로 동작한다.

 

1. 기본 생성자

-constructor 생략 가능

-기본 생성자는 코드를 갖지 못함(init 키워드로 생성자 표시)

-기본 생성자와 property를 함께 쓸 수 있음

ex)

1
2
3
4
5
6
7
8
class car(name : String){
    val name : String = name
    val speed : Int =0
}
 
//위 아래는 같은 코드임
 
class car(val name : String , val speed : Int=0)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class music constructor(genre : String, singer : String){
        val genre : String //parameter와 같은 이름의 매개 변수 사용 가능
        val singername : String
        init{
            this.genre=genre //this.genre는 music 클래스의 property
            this.singername=singer
        }
    fun print(){
        println("genre : ${this.genre}   singer : ${this.singername}")
    }
}
fun main(args : Array<String>){
    var mymusic=arrayOf(music("Rock","muse"),music("Pop","coldplay"),music("RnB","Khalid"))
    for(i in 0..mymusic.size-1){
        mymusic[i].print()
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

2. 보조 생성자

-기본 생성자를 보완하기 위해서 갖는 여러 개의 생성자

-constructor 키워드가 필요함

-this 키워드를 이요해서 기본 생성자 또는 다른 생성자에게 위임해야 함(delegation)

 

-실행 순서

 

 

 

728x90