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>代码>是代码>父< /代码>,所以编译器不把子类方法看作候选,因此它必须进行自动装箱,因为它只有一个候选方法,并且该方法需要自动装箱。不清楚您所指的“正确”是什么,既要创建对象,也要正确创建对象。