Java – How do I call an override method for a derived class (subclass)?

How do I call an override method for a derived class (subclass)?… here is a solution to the problem.

How do I call an override method for a derived class (subclass)?

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 do I get:

A new message parent method was called: msg: test message

What I want:

Call the new message submethod: msg: test message

  • I’m watching a thread and if I get a new message, I have to display it on the UI
    I observe this thread in the base activity because observing in each child activity (21 activities) it will be highly redundant and unmanageable.

  • I didn’t abstract the parent method to call the child method, because then every activity (a child activity of a baseactivity) must implement the method.
    I want the method to stay in the base class, after the call there will be a generic operation, and then if the method has any implementation (override), that data will be passed to the subclass

Now, I don’t know how this is possible, if it’s possible in the context of Java, Kotlin, please guide.

Thanks for your help. 🙂

Solution

By default, the JVM calls your child overridden methods, and the overridden methods can decide whether to call the parent class methods, which is how inheritance works. But to call the method you override, you have to make sure you’ve covered it!

In your code, you did not BaseActivity declare your onNewMessage method openin . So the compiler assumes that the method is final and does not allow it to be overwritten, so it replaces

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

and

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

So it can be overwritten with the same signature.

Related Problems and Solutions