Object (오브젝트)
정의
- 생성자 없이 객체를 직접 만들어내는 것 (인스턴스를 생성하지 않고 그 자체로 객체이다.)
- 공통적인 속성과 함수를 사용해야하는 코드에서는 굳이 class를 쓸 필요없이 object 사용
사용법
- object 이름에 참조 연산자를 붙여 사용
- object 이름.메소드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
object Counter{
//생성자 없다
var count = 0
fun countUp(){
count++
}
fun clear(){
count = 0
}
}
fun main() {
println(Counter.count)
Counter.countUp()
Counter.countUp()
println(Counter.count)
Counter.clear()
println(Counter.count) //출력결과: 0, 2, 0
}
Companion Object
- 기존 클래스 안에서도 오브젝트를 만들 수 있다.
- 클래스의 인스턴스 기능은 그대로 사용하면서 인스턴스 간에 공용으로 사용할 속성과 함수를 별도로 만드는 기능
- 기능적으로는 기존의 언어들이 가진 Static 멤버와 비슷
- static 멤버: 클래스 내부에서 별도의 영역에 고정적으로 존재하여 인스턴스를 생성하지 않아도 공용으로 사용가능한 속성이나 함수
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class FoodPoll(val name: String){
companion object{
var total = 0
}
var count = 0
fun vote(){
total++
count++
}
}
fun main() {
var a = FoodPoll("Rice")
var b = FoodPoll("Noodle")
a.vote()
a.vote()
a.vote()
b.vote()
b.vote()
println("${a.name}: ${a.count}")
println("${b.name}: ${b.count}")
println("총계 : ${FoodPoll.total}") //출력결과: 2,3,5
}