Java超类调用子类方法 [英] Java superclass calls subclass method
本文介绍了Java超类调用子类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这些课程:
class A {
public void f() { System.out.println("f() in A"); }
public void g() { System.out.println("g() in A"); f(); }
}
class B extends A {
public void f() { System.out.println("f() in B"); }
}
为什么
B b = new B();
A a = b;
a.g();
打印出此
g() in A
f() in B
不是
g() in A
f() in A
有什么我想念的吗?
推荐答案
是的,即使变量"a"的类型为A,但其持有的对象引用的类型也为B,因此B中的f()称为.
Yes, even though variable "a" is of type A, the object reference it holds is of type B, so f() in B is what's called.
这篇关于Java超类调用子类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文