굥뷰를 햡시댜

[Kotlin] Class 본문

언어/Kotlin

[Kotlin] Class

GodZ 2019. 4. 24. 04:51

1. 클래스

  • 클래스는 class 키워드로 선언
//class, 클래스 이름, 클래스 헤더(형식 매개변수, 기본 생성자 등), 클래스 바디로 구성
class Invoice(data: Int) {
}
  • 헤더와 바디는 옵션, 바디가 없으면 {} 생략 가능
class Empty

 

*Kotlin에서는 기본 생성자와 보조생성자가 분리됨 -> 이것들을 좀 잘 알아놔야 합니다!!

 

2. 기본 생성자(Primary Constructor)

  • 클래스 별로 1개만 가질 수 있음
  • 클래스 헤더의 일부
  • 클래스 이름 뒤에 작성
class Person constructor(firstName: String) {
}
  • 어노테이션이나 접근지정자가 없을 때는, 기본생성자의 constructor 키워드를 생략가능
class Person(firstName: String) {
}
  • 기본 생성자는 코드를 가질 수 없음
  • -> 초기화는 초기화(init)블록 안에서 작성해야 함
  • -> 초기화 블록init 키워드로 작성
  • 기본 생성자의 parameter는 init 블록 안에서 사용 가능
class Customer(name: String) {
    init {
        logger.info("Customer initialized with value ${name}")
    }
}
  • 기본 생성자의 parameter는 property 초기화 선언에도 사용 가능
class Customer(name: String) {
    val customerKey = name.toUpperCase()
}
  • property 선언 및 초기화는 기본 생성자에서 간결한 구문으로 사용 가능
class Person(val firstName: String, val lastName: String) {
	//....
}
  • 기본 생성자에 어노테이션 접근지정자 등이 있는 경우 constructor 키워드가 반드시 필요함
class Customer public @Inject constructor(name: String) { ... }

 

3. 보조 생성자

  • 클래스 별로 여러 개를 가질 수 있음
  • constructor 키워드로 선언
class Person {
    constructor(parent: Person) {
        parent.children.add(this)
    }
}
  • 클래스가 기본 생성자를 가지고 있다면, 각각의 보조 생성자들은 기본 생성자를 직접 or 간접적으로 위임해 줘야 함
  • this 키워드를 이용
  • 직접적 : 기본 생성자에 위임
  • 간접적 : 다른 보조 생성자에 위임
class Person(val name: String) {
    constructor(name: String, parent: Person): this(name) {
        //....
    }
    
    constructor(): this("홍길동", Person()) {
        //....
    }
}

 

4. 생성된(generated) 기본 생성자

  • 클래스에 기본 생성자 or 보조 생성자를 선언하지 않으면, 생성된 기본 생성자가 만들어집니다.
  • generated primary constructor -> parameter가 없음, 가시성이 public임 
  • 만약 생성된 기본 생성자의 가시성이 public이 아니어야 한다면, 다른 가시성을 가진 빈 기본 생성자를 선언해야함
class DontCreateMe private constructor() {
}

 

5. 인스턴스 생성

  • 코틀린은 new 키워드가 없음
  • 객체를 생성하려면 생성자를 일반 함수처럼 호출하면 된다.
val invoice = Invoice()

val customer = Customer("Joe Smith")

 

6. 클래스 멤버

  • 클래스에는 다음과 같은 것들을 포함할 수 있습니다.
  1. Constructors and initializer blocks (생성자와 초기화 블럭)
  2. Functions
  3. Properties
  4. Nested and Inner Classes (중첩 클래스 or 내부 클래스)
  5. Object Declarations (객체 선언)

'언어 > Kotlin' 카테고리의 다른 글

[Kotlin] Properties and Fields  (0) 2019.04.25
[Kotlin] Inheritance  (0) 2019.04.24
[Kotlin] Packages, Return and Jumps  (0) 2019.04.24
[Kotlin] Control Flow  (0) 2019.04.24
[Kotlin] Basic Types  (0) 2019.04.23
Comments