如果我有两个类,A 和 B,
public class A {
public int test() {
return 1;
}
}
public class B extends A{
public int test() {
return 2;
}
}
如果我这样做:A a1 = new B()
,那么 a1.test()
会根据需要返回 2 而不是 1。
这只是 Java 的一个怪癖,还是有某种原因导致这种行为?
最佳答案
这叫做 polymorphism .在运行时,将根据 a1
的“真实”类型调用正确的方法,在本例中为 B
。
正如维基百科所说:
The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run-time (this is called late binding or dynamic binding).
关于尝试使用父类方法时Java调用子类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12266744/