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
I am observing a thread, if a new message is received, I’ll have to show it on UI
I am observing this thread in base activity because observing in every child activity (21 activities), it will be highly redundant and difficult to manage.I did not make the parent method abstract so that child’s one will be called, because then every activity (child of BaseActivity) will have to implement that method. I want the method to stay in base class, and there will be universal operation after invoked, and then that data will be passed on to child class if it has any implementation of that method (overridden)
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. 🙂
Advertisement
Answer
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.