【问题标题】:Method overloading with Parent and Child class as parameter [duplicate]以父类和子类作为参数的方法重载[重复]
【发布时间】:2014-08-03 00:30:45
【问题描述】:

我有 3 个课程 GrandParentParentChild,其中 Child extends ParentParent extends GrandParent

public class Main {
    void test(GrandParent gp){System.out.println("GrandParent");}
    void test(Parent p){System.out.println("Parent");}

    public static void main(String args[]){
        GrandParent obj = new Child();
        Main mainObj = new Main();
        mainObj.test(obj);  // This calls test(GrandParent gp)

        mainObj.test(new Child()); // This calss test(Parent gp)
    }
}

在上面的代码中,对test() 方法的两次调用都与Child 对象调用了不同的方法。一方面,它在编译时和其他运行时绑定。这对我来说听起来有点奇怪。你会怎么解释这个?

【问题讨论】:

  • 呃,在我看来,这两种情况下都是编译时绑定……看看方法重载是如何解决的,应该有一个答案漂浮在某个地方
  • 两种情况的编译时间...

标签: java inheritance polymorphism overloading


【解决方案1】:

方法重载是编译时多态性。

方法覆盖是运行时多态性。

在您的情况下,您正在重载类Main 的两个实例方法。

但是,由于我假设在您的上下文中 Child 扩展了 Parentnew Child() instanceof Parent == true 因此 Child 的实例是方法 test 的有效参数,参数类型为 Parent

在您的第一种情况下,您在方法test 中传递了一个引用类型GrandParent,并找到了确切的类型。

在第二种情况下,您在方法test 中传递了一个引用类型Child。最接近的匹配是Parent,因此会调用test(Parent p)

【讨论】:

    【解决方案2】:

    重载意味着同名不同的参数。 例如:

          class A {
              public void m1(int a) {
                  System.out.println("class A");
              }
              public void m1(int a,int b) {
                  System.out.prinln("2 parameter");
              }
          }
    

    这称为方法重载。

    【讨论】:

    • 没错,但这并不能完全回答 OP 的问题。
    【解决方案3】:

    我认为你对你的层次结构感到困惑。

    你说的事实: Child 继承 Parent - 这意味着 Child“是”Parent。

    鉴于这在“现实世界”中没有意义 - 但是,它在您的代码中有意义 - 您正在为 void test(Parent p) 方法提供一个 Child 对象 - 因为 Child 是父级 - 这就是调用 System.out.println("Parent") 的原因。

    【讨论】:

    • 但是Child 也是这个层次结构中的Grandparent,对吧?那么为什么调用Parent 方法而不是Grandparent 方法呢?您在技术上是正确的,但您并没有完全回答 OP 的问题。
    • 我会假设给定另一个匹配的声明,比如提供 Child 对象的 void test(Object o) 将调用此方法,因为 Child 类隐式扩展 Object。然而,我可能是错的。
    • 取决于我是否和你有同样的想法,如果你做了test(new Child()),它实际上不会。如果您将 new Child() 分配给 Object 并通过了它,我想它会的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2017-02-02
    • 2020-04-26
    相关资源
    最近更新 更多