Let's take a look at this code:
public class ParentClass {
public void foo(Object o) {
System.out.println("Parent");
}
}
public class SubClass extends ParentClass {
public void foo(String s) {
System.out.println("Child");
}
public static void main(String args[]) {
ParentClass p = new SubClass();
p.foo("hello");
}
}
I expected this to print out "Child", but the result is "Parent". Why does java call the super class instead, and what do I do to make it call the method in the subclass?
SubClass#foo()
does not override ParentClass#foo()
because it doesn't have the same formal parameters. One takes Object
and the other takes a String
. Therefore polymorphism at runtime is not applied and does not cause the subclass method to execute. From the Java Language Specification :
An instance method
m C
declared in or inherited by class C, overrides from C another methodm A
declared in class A, iff all of the following are true:
A is a superclass of C.
C does not inherit
m A
.The signature of
m C
is a subsignature (§8.4.2) of the signature ofm A
....
And this section defines method signatures:
Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.
The signature of a method
m 1
is a subsignature of the signature of a methodm 2
if either:
m 2
has the same signature asm 1
, orthe signature of
m1
is the same as the erasure (§4.6) of the signature ofm 2
.
The parent class has no method with the signature public void foo(String s)
. Therefore, at compile time, the compiler can only choose the public void foo(Object o)
method for executing p.foo("hello")
.
Since the child class doesn't override this method (it doesn't have the same parameter type), the parent class's foo
method is the one executed at runtime.
字符串是java中的对象,因为它没有被覆盖,但是当你传递一个字符串时,它将运行第一个可用于参数的方法,在这种情况下它是超类的方法。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.