@CallSuper

홍성덕·2024년 7월 31일

프로젝트에서 BaseActivity, BaseFragment를 만들다가 @CallSuper라는 어노테이션을 알게되었다. @CallSuper는 class를 상속 혹은 interface를 구현할 때 override 메서드가 super 메서드를 invoke(호출)해야 함을 나타내는 어노테이션이다.

abstract class Animal {
	@CallSuper
    open fun makeSound() {
        println("making sound...")
    }
}

class Dog : Animal() {
    override fun makeSound() {
	    super.makeSound()
        println("멍멍!")
    }
}

class Cat : Animal() {
    override fun makeSound() { // Overriding method should call super.makeSound 오류 발생
        println("야옹~")
    }
}

이렇게 상위 클래스의 메서드에 @CallSuper를 사용하면, 하위 클래스에서는 무조건 상위 클래스의 메서드를 호출해야 한다. 호출하지 않으면 Overriding method should call super.메서드명 오류가 발생한다.

interface Animal {
    @CallSuper
    fun makeSound() {
        println("making sound...")
    }
}

abstract class나 open class뿐만 아니라 interface에서도 @CallSuper를 사용 가능하다. 마찬가지로 구현 클래스에서 무조건 interface의 해당 메서드를 호출해야 한다.

interface Animal {
    @CallSuper
    fun makeSound() {
        println("making sound...")
    }
}

class Dog : Animal {
    override fun makeSound() {
        super.makeSound()
        println("멍멍!")
    }
}

// ...

fun main() {
    val dog = Dog()
    dog.makeSound()
}

// 출력 결과
// making sound...
// 멍멍!

생명주기 콜백 메서드에서의 사용

우리가 흔히 아는 액티비티나 프래그먼트 생명주기 콜백 메서드 중에도 @CallSuper가 사용되는 메서드가 있다. 예를 들면 액티비티의 onCreate(), onResume(), 프래그먼트의 onDestroyView() 등이 있다. 예시로 onDestroyView() 코드를 가져왔다.

@MainThread
@CallSuper
public void onDestroyView() {
	mCalled = true;
}

하지만 모든 생명주기 콜백 메서드에 @CallSuper가 사용되는 것은 아니다. 예를 들어 프래그먼트의 onCreateView()에서는 @CallSuper가 사용되지 않았다.


참고자료

profile
안드로이드 주니어 개발자

0개의 댓글