当我无法使用基类引用调用派生类方法时,动态多态性有什么用? [英] How is dynamic polymorphism useful when I cant call derived class methods with base class reference

查看:110
本文介绍了当我无法使用基类引用调用派生类方法时,动态多态性有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()时,我理解了Btest()方法,这有助于防止代码中的条件语句.但是,假设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().

推荐答案

让我们以类AnimalBird为例,而不是类AB.

Rather than classes A and B let's use classes Animal and Bird for an example.

说您的Animal类具有方法eatsleep(所有动物都可以执行的操作),而Bird类也具有fly方法(仅鸟类可以执行).如果您引用了Animal对象,则无法对该变量调用fly方法是没有意义的,因为您不知道它是哪种动物,它可能是SlugWombat.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆