티스토리 뷰

코틀린(Kotlin) | 추상 클래스

  • 추상 클래스는 하나 이상의 추상 메서드(구현체가 없는 메서드)를 가진다.
  • 추상 클래스는 객체를 생성할 수 없다.
  • 추상 클래스를 상속하여 모든 추상 메서드를 구현하여야만 객체를 생성 할 수 있다.
  • 코틀린에서 추상 클래스란 abstract클래스 내부에 abstract멤버를 하나 이상 가진 클래스를 의미한다.
  • open키워드를 따로 추가하지 않아도 된다.
abstract class Animal {
    abstract fun bark()
    fun eat() {
        println("animal is eating")
    }
}

class Dog : Animal() {
    override fun bark() {
        println("bow wow")
    }
}

fun main() {
    val animal = Dog()
    animal.bark() // bow wow
    animal.eat() // animal is eating
}

인터페이스

  • Java8 인터페이스와 유사함.
  • 추상 메서드 또는 구현이 있는 메서드(default method)를 가질 수 있다.
  • 추상 프로퍼티(상태값) 또는 접근자를 가지는 프로퍼티를 가질 수 있다.
  • 여러 interface를 상속시 메서드의 시그니쳐가 중복된다면 반드시 구현 클래스에서 오버라이드 해주어야한다. (관련 URL)
interface Animal {
    // abstract property
    val name: String

    // accessor property
    val eat: String
        get() = "eating"

    // abstract method
    fun bark()

    // default method
    fun walk() {
        println("${this.name} is walk")
    }
}

class Dog(override val name: String) : Animal {
    override fun bark() {
       println("bow wow")
    }
}

fun main() {
    val dog: Animal = Dog("dog")

    println("dog eat :: ${dog.eat}") // dog eat :: eating
    dog.walk() // dog is walk
    dog.bark() // bow wow
}

 


출처

https://altongmon.tistory.com/588

 

코틀린(kotlin) : 인터페이스 Interface

공감 및 댓글은 포스팅 하는데 아주아주 큰 힘이 됩니다!! 포스팅 내용이 찾아주신 분들께 도움이 되길 바라며 더 깔끔하고 좋은 포스팅을 만들어 나가겠습니다^^ 이번 포스팅에서는 코틀린의 인터페이스에 대해서..

altongmon.tistory.com

https://androidtest.tistory.com/106

 

코틀린 기초 문법) 15. 코틀린 추상 클래스 및 인터페이스

자바에서 추상 클래스 및 추상 메서드 클래스 앞에 abstract 키워드를 이용하여 추상 클래스로 정의한다. 추상 메서드도 리턴 타입 앞에 abstract 키워드를 이용하여 추상 메서드를 정의한다. 추상 클래스에 추상..

androidtest.tistory.com

https://brunch.co.kr/@mystoryg/15

 

코틀린(Kotlin) 추상클래스 & 인터페이스

빠르게 살펴보기 | 추상 클래스 (Abstract Class) 클래스와 일부 멤버가 abstract로 선언되면 추상 클래스입니다. abstract 멤버는 아시다시피 클래스 내에서 아무런 구현이 없습니다. abstract class Student { abstract fun learnKotlin() // 최소 하나 이상의 멤버가 abstract fun learnJava() {}

brunch.co.kr

 

댓글