How to choice what method should be called when use polymorphism

Daniel Torres Aguilar :

I need a way to choice who method should be called.

I'm calling a parent method who calls one of its methods using "this". The problem is that I override that method in my class so when call the parent method then It calls to my method instead of its method.

public class MainTest    
{
    public static class A
    {
       public String m1()
       {
             return this.m2();
       }

       public String m2()
       {
           return "A.m2() called";
       }
    }

    public static class B extends A
    {
        @Override
        public String m1()
        {
          return "B.m1() called";
        }

        @Override
        public String m2()
        {
          return "B.m2() called";
        }

        public String m3()
        {
          return super.m1();
        }
    }

    public static void main(String[] args)
    {
        System.out.println(new B().m3());
    }
}

I want to achieve "A.m2() called", but the actual output is "B.m2() called"

ernest_k :

As you have overridden m2() in B, then only way to get A.m2() to run instead of B.m2() is to call super.m2() inside B.m2().

Even if you're calling super.m1(); in B.m3(), the call to this.m2() in A.m1() will still cause the overridden B.m2() to run.

If you don't want to have super.m2() inside B.m2() (or don't want that in all cases), then the only alternative is to create a different method that you don't override in B (and call that from A.m1() - you may have to change or create another A.m1() too):

public static class A {
   public String m1(){ //you may need a different method to call from B.m3()
       return this.anotherM2();
   }
   public String m2(){
       return "A.m2() called";
   }
   public String anotherM2() {
       return "A.m2() called";
   }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=152718&siteId=1