为什么要使用多态? [英] Why to use Polymorphism?

查看:119
本文介绍了为什么要使用多态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,其中有一个父类及其子类。我试图确定代码如何从使用多态性中受益。

I have the following code in which I have a parent class and its child. I am trying to determine how the code benefits from using polymorphism.

class FlyingMachines {
    public void fly() {
        System.out.println("No implementation");
    }
}

class Jet extends FlyingMachines {
    public void fly() {
        System.out.println("Start, Taxi, Fly");
    }

    public void bombardment() {
        System.out.println("Throw Missile");
    }
}

public class PolymorphicTest {
    public static void main(String[] args) {
        FlyingMachines flm = new Jet();
        flm.fly();

        Jet j = new Jet();
        j.bombardment();
        j.fly();
    }
}

当两个<$ c时,多态性有什么好处? $ c> flm.fly()和 j.fly()给我相同的答案?

What is the advantage of polymorphism when both flm.fly() and j.fly() give me the same answer?

推荐答案

让我们首先看一下OO设计,继承代表一种IS-A关系,通常我们可以说让我们的 FlyingMachines 飞。每个特定的 FlyingMachines (子类)IS-A FlyingMachines (父类),假设 Jet ,适合这个让我们的 FlyingMachines 飞,而我们希望这个飞行实际上是特定的(子类)的飞行功能,这是多态性接管。

let's look at OO design first, inheritance represents a IS-A relationship, generally we can say something like "let our FlyingMachines fly". every specific FlyingMachines (sub class) IS-A FlyingMachines (parent class), let say Jet, fits this "let our FlyingMachines fly", while we want this flying actually be the fly function of the specific one (sub class), that's polymorphism take over.

所以我们以抽象的方式做事,面向接口和基类,实际上并不依赖于细节实现,多态会做正确的事!

so we do things in abstract way, oriented interfaces and base class, do not actually depend on detail implementation, polymorphism will do the right thing!

这篇关于为什么要使用多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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