当我无法使用基类引用调用派生类方法时,动态多态性有什么用? [英] How is dynamic polymorphism useful when I cant call derived class methods with base class reference
问题描述
public class A {
protected int x = 10;
A() {
System.out.println("Constructor A" ) ;
}
public void test() {
System.out.println(" A " );
}
public void Aex() {
System.out.println(" Aex " ) ;
}
public void testg() {
System.out.println("Hello");
}
}
public class B extends A {
B() {
System.out.println("Constructor B" ) ;
}
B(int num){
this.x = num ;
//System.out.println(this.x);
}
public void test() {
System.out.println(" B " );
}
public int getx() {
return this.x;
}
}
public class C {
public static void main( String [] args ) {
A a = new B();
//a.test();
a.Aex();
//a.testg();
B b = new B(5);
a = b;
a.test();
System.out.println( a.getx() ) ;
}
}
类B
从类A
继承,并且都具有称为test()
的方法.我可以创建对派生类对象的基类引用,因此可以创建引用A a = new B();
.当我调用a.test()
时,我理解了B
的test()
方法,这有助于防止代码中的条件语句.但是,假设B
有另一个名为void getx()
的方法,并且我想调用该方法,因为基类没有称为void getx()
的方法,所以我不能使用基类引用来调用它.那么在这种情况下多态性有什么用呢?调用getx
的唯一方法是创建派生类的引用并调用getx()
.
Class B
inherits from class A
and both have a method called test()
. I can create a base class reference to a derived class object , so I create a reference A a = new B();
. When I call a.test()
, the test()
method of B
is called which I understand , which helps me to prevent conditional statements in my code. But suppose B
has another method called void getx()
, and I want to call that method, I cannot call it with a base class reference , since the base class has no method called void getx()
. So how is polymorphism useful in such a situation ? The only way to call getx
is to create a reference of derived class and call getx()
.
推荐答案
让我们以类Animal
和Bird
为例,而不是类A
和B
.
Rather than classes A
and B
let's use classes Animal
and Bird
for an example.
说您的Animal
类具有方法eat
和sleep
(所有动物都可以执行的操作),而Bird类也具有fly
方法(仅鸟类可以执行).如果您引用了Animal
对象,则无法对该变量调用fly
方法是没有意义的,因为您不知道它是哪种动物,它可能是Slug
或Wombat
.
Say your Animal
class has methods eat
and sleep
(things that all animals do) and your Bird class also has a fly
method (which only birds can do). If you have a reference to an Animal
object it would make no sense to be able to call the fly
method on this variable because you don't know what kind of animal it is, it could be a Slug
or an Wombat
.
这篇关于当我无法使用基类引用调用派生类方法时,动态多态性有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!