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 변수처럼 사용하기
fun kotlin() { 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 |
'프로그래밍 > Kotlin' 카테고리의 다른 글
코틀린 Getters and Setters #2 (0) | 2017.12.10 |
---|---|
코틀린(Kotlin) Getters and Setters #1 (0) | 2017.12.10 |
코틀린(Kotlin) 클래스 상속 (0) | 2017.12.09 |
코틀린(Kotlin) 클래스 선언 방법 #2 (0) | 2017.12.07 |
코틀린(Kotlin) 클래스 선언 방법 #1 (0) | 2017.12.05 |
코틀린(Kotlin) 변수 선언 방법 빠르게 살펴보기 (0) | 2017.12.04 |
Layout Preview 안보이는 문제 (0) | 2017.11.29 |