안드로이드 개발자의 창고
[15일차 Kotlin] 추상화(abstract) 본문
출처 : 안드로이드 앱스쿨 2기 윤재성 강사님 수업 PPT
📖 추상화
- 추상 클래스 : 추상 메서드를 가지고 있는 클래스
- 추상 메서드 : 구현되지 않은 메서드
- 추상 클래스는 구현 되지 않은 추상 메서드를 가지고 있기 때문에 완벽한 설계도라고 할 수 없다.
- 때문에 추상 클래스는 객체를 생성할 수 없다.
- 추상 클래스를 상속받은 클래스를 만들고 추상 메서드를 오버라이딩하여 사용한다.
- 추상 메서드에는 open 키워드를 사용해야 한다.
- 추상 클래스와 메서드는 abstract 키워드를 사용하며 상속이 가능해야 한다.
- 클래스에는 open 키워드를 사용해야 오버라이딩이 가능하다.
- 추상 클래스는 메서드 오버라이딩에 대한 강제성을 주기 위해 사용한다.
📖 예제 코드
fun main() {
val t2 = TestClass2()
t2.testMethod() // TestClass2의 testMethod
val t3:TestClass1 = TestClass2()
t3.testMethod() // TestClass2의 testMethod
}
// 추상 클래스
open abstract class TestClass1{
// 추상 메서드
open abstract fun testMethod()
}
// 추상 클래스를 상속 받은 클래스
class TestClass2 : TestClass1(){
override fun testMethod() {
println("TestClass2의 testMethod")
}
}
✔️ 코드 해석
- TestClass2는 추상 클래스인 TestClass1을 상속 받았다.
- TestClass1에서 testMethod()는 추상 메서드로 오버라이딩을 강제하고 있다.
- 따라서 TestClass2의 testMethod()는 TestClass1의 testMethod()를 오버라이딩한 메서드이다.
- t2.testMethod()
- t2는 TestClass2의 객체이므로 TestClass2의 testMethod()가 호출된다.
- t3.testMethod()
- TestClass2의 인스턴스를 생성하여 부모 클래스인 TestClass1의 t3에 저장하였다.
- t3의 testMethod()를 호출하면 TestClass1의 메서드가 호출된다.
- 그러나 TestClass1의 testMethod()는 오버라이딩 됐기 때문에 TestClass2의 testMethod()가 호출된다.
'Computer > Kotlin' 카테고리의 다른 글
[16일차 Kotlin] Companion (0) | 2023.05.18 |
---|---|
[15일차 Kotlin] 인터페이스(Interface) (0) | 2023.05.17 |
[15일차 Kotlin] Any (0) | 2023.05.17 |
[14일차 Kotlin] Overriding(오버라이딩) (0) | 2023.05.17 |
[14일차 Kotlin] 지연 초기화 - lateinit과 lazy (0) | 2023.05.17 |