简体   繁体   中英

Why is my Child Class method is being calling always whenever I trigger an action in the Parent Class - Android?

I'm trying to inherit a Parent call (say A) to my child class (say B). Furthermore, my Parent Class is interfaced by an other class so, in short my Parent Class has some @Override methods and its implementation. Also, my Child class is interfaced by the same class as that of Parent class but with different implementation.

The problem is that when I try to trigger any action form Parent class, it checks its response from Child class rather than Parent class itself.

I want that Parent class should handle its own actions and Child class should handle its own. Is is possible or is there any way to achieve it?

I hope you got my problem. It's all about inheritance and interface implementation. Here's below my code sample:

Parent Class: A

public class A extends AppCompatActivity implements VolleyJsonRespondsListener{

    @Override
    public void onSuccessJson(String response, String requestName) {

        switch (requestName) {

            case "abc":
            CommonFunctions.showToastTest(context, "abc toast");

            break;
        }
}

Child Class: B

public class B extends A implements VolleyJsonRespondsListener {

        @Override
        public void onSuccessJson(String response, String requestName) {

            switch (requestName) {

                case "xyz":
                CommonFunctions.showToastTest(context, "xyz toast");

                break;

            }

}

One of the solution is this but I don't want this

public class B extends A implements VolleyJsonRespondsListener {

            @Override
            public void onSuccessJson(String response, String requestName) {

                switch (requestName) {

                    case "xyz":
                    CommonFunctions.showToastTest(context, "xyz toast");

                    break;

                    case "abc":
                    CommonFunctions.showToastTest(context, "abc toast");

                    break;
                }

    }

I think you can change your code as follows:

// Don't need "implements VolleyJsonRespondsListener" because A already implemented it. So, just override onSuccessJson
public class B extends A {

    @Override
    public void onSuccessJson(String response, String requestName) {
        if("xyz".equals(requestName)) {
             // Child class expects "xyz". Handle it.
             CommonFunctions.showToastTest(context, "xyz toast");
        } else {
            // requestName not expected by Child class. Delegate to parent via super.onSuccessJson();
            super.onSuccessJson(response, requestName);
        } 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM