Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 27 | 28 |
Tags
- BOJ
- Coroutine
- AppBarLayout
- activity
- Algorithm
- 백준
- 알고리즘
- CollapsingToolbarLayout
- Navigation
- Android
- 알림
- LiveData
- notification
- kotlin
- recyclerview
- CoordinatorLayout
- 코틀린
- hilt
- ViewModel
- lifecycle
- onMeasure
- 안드로이드
- room
- View
- Behavior
- HTTP
- CustomView
- sqlite
- onLayout
- DataBinding
Archives
- Today
- Total
개발일지
Kotlin in A..Z (14) - 상속 본문
- 상속
상속을 하면 부모 클래스의 프로퍼티와 메서드를 불려받는다.
open 키워드를 붙여서 상속 시킬 수 있다.
코드
open class Parent(val name: String) {
}
class Child(name: String) : Parent(name) {
}
fun main() {
val child = Child("개발일지")
println(child.name)
}
결과
개발일지
자바는 open 키워드를 안붙여도 상속 시킬 수 있고, final 키워드를 붙여야 최하위 클래스가 되지만, 코틀린은 open 키워드를 붙여야 상속 시킬 수 있고, open 키워드를 붙이지 않으면 최하위 클래스가 된다.
- 메소드 오버라이딩
open과 override 키워드를 통해 부모의 클래스로 부터 상속받은 메서드를 자신에게 맞게 수정할 수 있다.
코드
open class Parent() {
open fun action() {
println("Parent")
}
}
class Child() : Parent() {
override fun action() {
println("Child")
}
}
fun main() {
val parent = Parent()
parent.action()
val child = Child()
child.action()
}
결과
Parent
Child
- super와 this
super은 부모 클래스를 뜻하고, this는 자기 자신을 뜻한다.
super로 부모의 프로퍼티와 메소드를 참조할 수 있고, this로 자기 자신의 프로퍼티와 메소드를 참조할 수 있다.
코드
open class Parent() {
open fun action() {
println("Parent")
}
}
class Child() : Parent() {
override fun action() {
println("Child")
}
fun func() {
super.action() // 부모의 action을 참조
this.action() // 자신의 action을 참조
action() // 자신의 action을 참조, 자신의 프로퍼티와 메소드를 참조할 땐 생략가능
}
}
fun main() {
val child = Child()
child.func()
}
결과
Parent
Child
Child
'Kotlin (코틀린)' 카테고리의 다른 글
Kotlin in A..Z (16) - 프로퍼티 getter, setter (0) | 2020.07.15 |
---|---|
Kotlin in A..Z (15) - 가시성 지시자 (0) | 2020.07.15 |
Kotlin in A..Z (13) - 클래스 (0) | 2020.07.15 |
Kotlin in A..Z (12) - for, while, do ~ while (0) | 2020.07.15 |
Kotlin in A..Z (11) - when (0) | 2020.07.15 |
Comments