java java中多态的例子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5962364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:41:54  来源:igfitidea点击:

example of polymorphism in java

javaooppolymorphism

提问by user748394

I'm beginner in Java, so, i'm sorry if the question will be too simple for you.

我是 Java 初学者,所以,如果问题对您来说太简单,我很抱歉。

Could somebody explain me what the polymorphism is in Java? I need just piece of codethat describes it simply.

有人可以解释一下 Java 中的多态性是什么吗?我只需要一段简单描述它的代码

Thank you.

谢谢你。

采纳答案by Cogsy

Looks like homework to me, but I'm bored and Java makes me nostalgic.

对我来说看起来像是家庭作业,但我很无聊,Java 让我怀旧。

List<A> list = new ArrayList<A>();
list.add(new A());
list.add(new A());
list.add(new B());

public void printAll() {
    for(A i : list) {
        System.out.println(i.print());
    }
}

class A {
    public String print() {
        return "A";
    }
}

class B extends A {
    @Override
    public String print() {
        return"B";
    }
}

The output would look like:

输出将如下所示:

    A
    A
    B

The polymorphic part is when different code is executed for the same method call. The loop does the same thing everytime, but different instance methods may actually be getting called.

多态部分是为同一个方法调用执行不同的代码。循环每次都做同样的事情,但实际上可能会调用不同的实例方法。

回答by Jad

There are several tutorials as already stated. Here's a quick example I hope is accurate (it's like answering a test)

如前所述,有几个教程。这是一个我希望是准确的快速示例(就像回答测试一样)

Parametric polymorphismThe same class defines more than one function with the same name but a different array of parameters. The parameter numbers and/or type make it possible to route the call to the right function.

参数多态性同一个类定义了多个具有相同名称但参数数组不同的函数。参数编号和/或类型可以将调用路由到正确的函数。

class PolyTest1 {
  private void method1(int a) {}
  private void method1(String b) {}
}

Inheritance polymorphismA class can redefine one of its parent class' methods. The object type makes it possible to call the right function.

继承多态一个类可以重新定义其父类的方法之一。对象类型使得调用正确的函数成为可能。

public class PolyTest2 extends PolyTest1{

  private void method1(String b) {}
}

回答by duffymo

Have a look at the JDK itself. You'll see polymorphism in lots of places, for example if you look at the java.util Collections. There's a java.util.List interface reference type can behave like an ArrayList or a LinkedList, depending on the runtime type you assign to it.

看看 JDK 本身。您会在很多地方看到多态性,例如,如果您查看 java.util 集合。有一个 java.util.List 接口引用类型可以像 ArrayList 或 LinkedList 一样运行,具体取决于您分配给它的运行时类型。

回答by RushabhM

The example given in 1st answer of this question makes concept clear. Have a look! Polymorphism vs Overriding vs Overloading

这个问题的第一个答案中给出的例子使概念清晰。看一看! 多态 vs 覆盖 vs 重载