javaandroidkotlinoopobject-oriented-analysis

How to call the overridden method of a derived class (child class)?


abstract class BaseActivity : AppCompatActivity() {
    funNewMessageObserver() {
        observable.observe(this, {
            onNewMessage(it) //where `it` is a string    
        }  
    }
    
    fun onNewMessage(msg : String){
        Log.e(TAG, "New Message Parent Method invoked: msg: $msg")  
    }
} //end of base activity

class ChatActivity : BaseActivity() {
    override fun onNewMessage(msg : String) {
        Log.e(TAG, "New Message Child Method invoked: msg: $msg")
    }
}

What Output I get:

New Message Parent Method invoked: msg: test message

What out I want:

New Message Child Method invoked: msg: test message

Right now, I can't find out how this would be possible, If there is a possibility in context of Java, Kotlin, kindly guide.

Help is appreciated. :)


Solution

  • JVM invokes your child overridden method by default and the overridden method can decide whether to call the super method or not, that's how inheritance works. But for your overridden method to get called you have to make sure you have overridden it!

    In your code you have not declared your onNewMessage method open in the BaseActivity. Hence the compiler assumes the method as final and does not allow overriding it, so replace

    fun onNewMessage(msg : String) {
        Log.e(TAG, "New Message Parent Method invoked: msg: $msg")  
    }
    

    with

    open fun onNewMessage(msg : String) {
        Log.e(TAG, "New Message Parent Method invoked: msg: $msg")  
    }
    

    So it can be overridden using the same signature.