zabdiel
zabdiel

Reputation: 11

Java Inheritance - sibling's overriding method issues

I have 4 classes, 1 parent class and 2 inheriting child(siblings), and one interface (service callback, that does something every set of time (e.g every 5 seconds), by the way this is done from Android development.

Ill post the 3 classes excluding the interface to reduce some codes

The Parent Class, BaseActivity.java

 public class BaseActivity extends Activity implements BackgroundServiceCallback{

     @Override
     public void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);
         BaseActivity.this.startBackgroundService();
     }

     @Override
     public void onBackgroundServiceCallback() {
         // no concrete implementation (will be implemented in child_a)
     }

     public void startBackgroundService() {
         // configure and start the service here
     }
}

An inheriting Child, ChildActivity_A.java

  public class ChildActivity_A extends BaseActivity {

     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // some activity configurations here.
     }

     @Override
     public void onBackgroundServiceCallback() {
         // concrete implementation goes here, and will work
     }
 }

as you can see above(what ever the background service is doing) the Child_A's concrete method(implementation will work every time a callback happens

now this is where it becomes tricky(on my perspective) here is the third class

An inheriting child ChildActivity_B.java

  public class ChildActivity_B extends BaseActivity {

     @Override
     public void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);
         // some activity configurations here.

         // if I call super.startBackgroundService() or this.startBackgroundService
         // ChildActivity_A's implementation is not being called
     }
 }

If i call the startBackgroundService from ChildActivity_B the concrete implementation on ChildActivity_A is not being called

I've been doing java programs way before android development, taking things for granted, I think i missed some things about inheritance that makes me confuse in this situation.

I just need some enlightenment on why does it happen, (By the way I resolved the real problem by setting a static flag in a custom Application class to start a service or not in an activity)

Upvotes: 1

Views: 465

Answers (1)

Gaurav Jeswani
Gaurav Jeswani

Reputation: 4582

In your code "BaseActivity.this.startBackgroundService()" is actually start background service, which is available in BaseActivity.java. In your ChildActivity_B you are calling it by super.onCreate(savedInstanceState);. So it will only call it's super method, which is available in it's super class BaseActivity.java, not ChildActivity_A. ChildActivity_B actually doesn't know anything about ChildActivity_A.

Upvotes: 1

Related Questions