brunch

You can make anything
by writing

C.S.Lewis

by 서준수 Dec 08. 2017

코틀린(Kotlin) 클래스 선언 방법 #3

빠르게 살펴보기

Properties and Fields


Properties 란?

 코틀린의 클래스는 properties를 가질 수 있습니다. Java로 생각하면 인스턴스 변수입니다. 멤버 변수라고 하지 않는 이유는 멤버 변수에 static 변수도 포함되기 때문입니다.


Java의 멤버 변수


 class Person {

   int id; // 인스턴스 변수 -> 멤버 변수

   String name; // 인스턴스 변수 -> 멤버 변수

   static int age; // static 변수, 클래스 변수 -> 멤버 변수

 }



 코틀린에서 properties는 다음과 같이 선언할 수 있습니다. Java와 변수 선언 방법만 다를 뿐 큰 차이가 없습니다.


 class Person {

  var id: Int = 0

  var name: String = "Suzuki"

 }



클래스의 인스턴스 생성하기

 properties 사용방법도 거의 동일합니다. 객체를 만들어서 Java의 field처럼 쉽게 변수명으로 부를 수 있습니다.


 val student = Person() // new 키워드를 사용하지 않음

 student.id = 10

 student.name = "Kim"



static 변수처럼 사용하기

 위에서 언급한 Java의 static 변수를 코틀린에서 유사하게 사용하는 방법이 있습니다. Companion Objects을 사용하면 됩니다. '클래스명.변수'로 접근하는 형태가 Java의 static 변수와 동일합니다.

 (Companion Objects에 대해서는 추후 공부해야 할 부분이네요.)                             


     fun main() {

        val student = Person()

        student.id = 10

        student.name = "Kim"

        Person.age = 20


        println("student.id = ${student.id}")

        println("student.name  = ${student.name}")

        println("Person.age = ${Person.age}")

    }


    class Person {

        var id: Int = 0

        var name: String = "Suzuki"

        companion object {

            var age: Int = 0

        }

    }


 student.id = 10

 student.name  = Kim

 Person.age = 20



이전 04화 코틀린(Kotlin) 클래스 선언 방법 #2
brunch book
$magazine.title

현재 글은 이 브런치북에
소속되어 있습니다.

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari