动态方法调用(继承中的对象和引用) [英] Dynamic Method invocation (Objects and reference in inheritance )
问题描述
假设我有2个类........ A
类是基类和类 B
是派生类,如果我创建一个引用,如: A a = new B(); 这意味着引用
a
指向 B Class
的对象?如果是的,我怎么能够调用B中的A的重写方法而不是B的其他方法?先谢谢你
Suppose I have 2 classes ........A
Class is base class and class B
is derived class and if i create a reference such as : A a=new B();
does it mean that reference a
points to object of B Class
? If yes than how am i able to call overridden methods of A in B and not other methods of B ? thank you in advance
class A {
m1() {
}
}
class B extends A {
m1() {
}
m2() {
}
}
A a=new B();
a.m1(); //it will call overridden m1() in B
a.m2(); //it doesnt work if reference "a" points to object of B than why doesnt it call m2 method ?
推荐答案
Animal a=new Dog(); // Animal is parent - class, Dog is a child
意味着你有一个动物引用指向狗对象。因此,只有在父类(Animal)中声明的方法可以使用父类引用来调用。
means, you have an animal reference pointing to a Dog Object. So, only the methods which are declared in the parent class (Animal) can be called using a parent- class reference.
在 A类
中未定义 m2()
,它只定义在 class B
因此,使用 A
的引用,不能调用 m2()
In your case, m2()
is not defined in Class A
, it is only defined in class B
so, using a reference of A
, you can't call m2()
这篇关于动态方法调用(继承中的对象和引用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!