繁体   English   中英

使用多态时如何选择调用什么方法

[英]How to choice what method should be called when use polymorphism

我需要一种方法来选择应该调用谁的方法。

我正在调用一个使用“this”调用其方法之一的父方法。 问题是我在我的类中覆盖了该方法,所以当调用父方法时,它会调用我的方法而不是它的方法。

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());
    }
}

我想实现“A.m2() 调用”,但实际输出是“B.m2() 调用”

正如你所覆盖的m2()B ,那么只有这样,才能A.m2()而不是运行B.m2()是调用super.m2()B.m2()

即使你正在调用super.m1(); B.m3()调用this.m2()A.m1()将仍然导致重写B.m2()来运行。

如果您不想在super.m2() B.m2() (或者在所有情况下都不想这样做),那么唯一的选择是创建一个您不在B覆盖的不同方法(并从A.m1()调用它 - 您可能也必须更改或创建另一个A.m1() ):

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

您可以看到以下过程:

-B.m3 做 super.m1 是什么意思 A.m1

-A.m1 执行 this.m2,这里是 B,因此调用 B.m2

为了实现你想要的,你需要在B.m3调用super.m2()

调用super.m1()不起作用,因为A.m1调用this.m2() this是运行时类型B (您从未创建过A对象,因此它不能是运行时类型A ),因此将调用Bm2 您只能调用super.m2()来实现您想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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