티스토리 뷰

오버라이드(Override) vs 오버로드(Overload)

오버라이드(Override)
  • 상위 클래스의 매소드를 재정의 하는 것.
  • 메소드 이름은 물론 인자 갯수나 타입도 동일해야 한다.
  •  주로 상위 클래스의 동작을 상속받은 하위클래스에서 메소드의 동작을 변경하기 위해 사용된다.
오버로드(Overload)
  • 함수(메소드이름은 같고 인자 갯수나 타입이 다른 함수를 정의하는 것을 의미한다.

메서드 오버라이드

  • 클래스 상속과 마찬가지로 기본 final이며 명시적으로 open키워드를 붙여 줘야만 오버라이드가 가능하다.
  • 오버라이드를 위해서는 명시적으로 override키워드를 붙여 주어야한다.
  • final클래스에서는 open멤버가 금지된다.
open class Parent {

    open fun walking() {
        println("person is walking")
    }

}


class Child : Parent() {

    override fun walking() {
        println("child is walking")
    }
}

fun main() {
    val child = Child()
    child.walking() // child is walking
}

 

  • 부모 클래스에서 open이 되어있지 않은 메서드는 override에 관계없이 동일한 시그니쳐로 선언하지 못한다.
open class Parent {

    fun eat() {
        println("person is eating")
    }

}


class Child : Parent() {

    fun eat() { // error
        
    }
}

 

  • override를 갖는 멤버는 그 자체로 open이며 하위 클래스에서 오버라이딩이 가능하다.
  • 만약 오버라이딩을 못하게 막고자 한다면 final키워드를 명시적으로 적어야한다.

 

open class Parent {
    open fun eat() {
        println("person is eating")
    }
}

open class Child : Parent() {
    override fun eat() { // none open keyword
        println("child is eating")
    }
}

class GrandChild : Child() {
    override fun eat() { // override Child.eat
        println("grandchild is eating")
    }
}

fun main() {
    val grandChild = GrandChild()
    grandChild.eat() // grandchild is eating
}

프로퍼티 오버라이드

  • 메서드 오버라이드와 비슷한 방법으로 동작한다.
  • 주요 생성자의 프로퍼티 선언부에서 override키워드를 사용할 수 있다.
open class Parent {
    open val age:Int = 30

    fun printAge() {
        println("my age is ${this.age}")
    }
}

class Child(override val age:Int): Parent() {

}

fun main() {
    val child = Child(50)
    child.printAge() // my age is 50

 

  • 여러 인터페이스(클래스)를 상속받을때 중복된 시그니쳐를 상속한다면 반드시 이 멤버를 오버라이드 해야한다.
interface A1 {
    fun a() { println("A1 class") }
}

interface A2 {
    fun a() { println("A2 class") }
}

class Klass: A1, A2 {
    override fun a() {
        super<A1>.a()
        super<A2>.a()
    }
}

fun main() {
    val klass = Klass()
    klass.a()
    //A1 class
    //A2 class
}

 


출처

https://androidtest.tistory.com/103

 

코틀린 기초 문법) 12. 코틀린 오버라이딩, 오버로딩 알아보기

오버로딩(Overloading)? 메서드(함수) 이름을 고정으로 하고 매개변수 만 다르게 함으로써 메서드를 여러개 만드는 것 자바에서 오버로딩 public class OverloadingClass { void ex(){} void ex(int x){} void ex(..

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

https://tourspace.tistory.com/106

 

[Kotlin] 코틀린 클래스, 인터페이스

이 글은 Kotlin In Action을 참고 하였습니다. 더욱 자세한 설명이나 예제는 직접 책을 구매하여 확인 하시기 바랍니다 코틀린은 Java와 같은 형태의 상속개념을 가집니다. 인터페이스와 객체등의 성격도 그대로..

tourspace.tistory.com

 

댓글