Java 为什么要调用父类方法?

Java 为什么要调用父类方法?,java,inheritance,overriding,covariance,Java,Inheritance,Overriding,Covariance,为什么在创建子对象时调用父类方法。这甚至不是一种静态方法 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[]

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

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
。但它还是转到父方法


任何解释?

当您调用
u.pubMethod(1)
时,编译器只考虑
Parent
类的方法的签名,因为
Parent
u
的编译类型。由于
publicstringpubMethod(Integer i)
Parent
中唯一具有所需名称的方法,因此这是所选的方法<子类的code>public String pubMethod(int i)不被视为候选,因为父类的
没有此类签名的方法

在运行时,子类
公共字符串pubMethod(int i)
的方法无法重写超类方法
公共字符串pubMethod(Integer 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)
,但在运行时,
子类方法将覆盖它


在第二种情况下,编译器将有两种方法可供选择。它将选择
publicstringpubMethod(inti)
,因为文本
1
的类型是
int
。在运行时,
子对象
公共字符串pubMethod(int i)
方法将覆盖它。

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

Parent child = new Child();
但你应该:

Child child = new Child();

但由于子类具有来自其父类和自己的类的方法访问权。我之前读过的是
“在执行过程中,它会尝试查找具有相同参数类型的匹配项,如果找不到,则只进行自动装箱”
。是吗?是的,Nicky,但是变量
u
的类型是
Parent
,而不是
Child
,因此它不能用于访问
Child
的方法,除了那些是
Parent
中方法的真正重写@Nicky是正确的(关于自动装箱),但是编译时类型<代码> u>代码>是代码>父< /代码>,所以编译器不把子类方法看作候选,因此它必须进行自动装箱,因为它只有一个候选方法,并且该方法需要自动装箱。不清楚您所指的“正确”是什么,既要创建对象,也要正确创建对象。