1. Answer
상속 선언에서 interface는 이름만 정의하면 됩니다. 왜냐하면 interface는 생성자가 없기 때문입니다.
// interface 정의
interface Clickable {
fun click()
}
class Button : Clickable {
override fun click() {
println("Button clicked!")
}
}
클래스는 부모 클래스의 Primary constructor를 호출하기 위해서 호출해야 합니다.
open class Animal(val name: String) {
}
class Dog(name: String) : Animal(name) {
}
class Cat(name: String) : Animal { // Compile 에러 발생합니다.
}
1. Background
Kotlin에서는 Primary Constructor 와 Secondary Constructor가 존재
- Primary constructor 클래스 이름 바로 옆에 오는 생성자 클래스 당 하나만 가질 수 있고, 파라미터에 val/var를 붙이면 자동 프로퍼티가 됩니다. 클래스 헤더의 일부(?) 입니다.
class Person(val name: String, val age: Int) {
// 초기화가 필요하다면 init 블록을 사용합니다.
init {
// something...
}
}
// 또는 constructor 키워드를 명시적으로 쓸 수 있음
class Person constructor(val name: String, val age: Int) {
}
- Secondary constructor 클래스 본문에 별도로 생성된 생성자 입니다. 만약, Primary와 Secondary가 같이있으면, Secondary는 반드시 Primary constructor를 호출해야 합니다.
class Person {
val name: String
val age: Int
constructor( name: String, age: Int) {
this.name = name
this.age = age
}
constructor(name: String) {
this.name = name
this.age = 0
}
}
상속
- 부모가 Primary Constructor만 소유하고 있을 때 자식은 당연히 부모의 Primary constructor 을 호출해야 합니다.
class Person(val name: String, val age: Int) {
}
class Student(name: String, age: Int, val number: Int) : Person(name, age) {
}