简体   繁体   中英

How to choice what method should be called when use polymorphism

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"

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";
   }
}

you can see the following process:

-B.m3 does super.m1 what means A.m1

-A.m1 does this.m2, where this is B, for that reason B.m2 is being called

To achieve what you want, you need to call super.m2() in B.m3 .

Calling super.m1() wouldn't work because A.m1 calls this.m2() . this is of runtime type B (you have never created an A object so it can't be of runtime type A ), so the m2 in B would be called. You can only call super.m2() to achieve what you want.

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