代码之家  ›  专栏  ›  技术社区  ›  Nicky

为什么调用父类方法?

  •  4
  • Nicky  · 技术社区  · 7 年前

    为什么在创建子对象时调用父类方法。这甚至不是静态方法。

    class Parent {
        public String pubMethod(Integer i) {
            return "p";
        }
    }
    
    public class Child extends Parent {
        public String pubMethod(int i) {
            return "c";
        }
    
        public static void main(String[] args) {
            Parent u = new Child();
            System.out.println(u.pubMethod(1));  // Prints "p"   why??
        }   
    }
    

    在这里我经过一个原始的 int 是的。仍然是父方法。

    有什么解释吗?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Eran    7 年前

    当你打电话 u.pubMethod(1) ,编译器只考虑 Parent 上课,因为 起源 是编译类型类型 u 是的。自从 public String pubMethod(Integer i) 是唯一的方法 起源 具有必需的名称,这是选定的方法。 public String pubMethod(int i) 属于 Child 类不被视为候选,因为 起源 没有这种签名的方法。

    在运行时,子类的方法, 公共字符串pubMethod(int i) ,无法重写超类方法 公共字符串pubMethod(整数i) ,因为它有不同的签名。因此 起源 执行类方法。

    为了 儿童 要执行的类,必须更改其签名以匹配 起源 类方法的签名,它将允许它重写 起源 类方法:

    public class Child extends Parent {
        @Override
        public String pubMethod(Integer i) {
            return "c";
        }
    }
    

    或者您可以将第二个方法添加到 起源 类,现有的 儿童 类方法将重写:

    class Parent {
        public String pubMethod(Integer i) {
            return "pInteger";
        }
        public String pubMethod(int i) {
            return "pint";
        }
    }
    

    在第一种情况下,编译器仍有一个方法可供选择- 公共字符串pubMethod(整数i) -但在运行时 儿童 类方法将重写它。

    在第二种情况下,编译器将有两种方法可供选择。它会选择 公共字符串pubMethod(int i) ,因为 1 int 是的。在运行时, 儿童 公共字符串pubMethod(int i) 方法将重写它。

        2
  •  -1
  •   main.c    7 年前

    我认为您没有正确创建子对象,您有:

    Parent child = new Child();
    

    但你应该:

    Child child = new Child();