在本教程中,我们将了解 Java 中的多态性。
Java 中的多态性是具有抽象、封装和继承的核心面向对象编程概念之一。
Polymorphism指一个名字多种形式。在Java中,多态可以通过方法重载和方法覆盖来实现。
Polymorphism
java中有两种类型的多态。
Compile time Polymorphism只不过是java中的方法重载。您可以定义具有相同名称但方法参数不同的各种方法。您可以阅读有关方法重载的更多信息。
Compile time Polymorphism
让我们在示例的帮助下理解:
package org.arpit.java2blog; public class MethodOverloadingExample { public void method1(int a) { System.out.println("Integer: "+a); } public void method1(double b) { System.out.println("Double "+b); } public void method1(int a, int b) { System.out.println("Integer a and b:"+a+" "+b); } public static void main(String args[]) { MethodOverloadingExample moe=new MethodOverloadingExample(); moe.method1(20); moe.method1(30.0); moe.method1(20, 30); } }
当你运行上面的程序时,你会得到下面的输出:
Integer: 20 Double 30.0 Integer a and b:20 30
正如您在此处看到的,我们使用了相同的方法名称但不同的方法参数。编译器将根据最佳匹配的参数调用适当的方法。
Runtime Polymorphism只不过是java中的方法覆盖。如果子类与基类具有相同的方法,那么它被称为方法覆盖或者换句话说,如果子类为其父类之一中存在的任何方法提供特定实现,那么它就是已知的作为method overriding.
Runtime Polymorphism
method overriding
假设您有父类 asShape和子类Rectangleand circle。
Shape
Rectangle
circle
package org.arpit.java2blog; public class Shape { public void draw() { System.out.println("Drawing Shape"); } public static void main(String[] args) { Shape s=new Rectangle(); s.draw(); s=new Circle(); s.draw(); } } class Rectangle extends Shape { public void draw() { System.out.println("Drawing Rectangle"); } } class Circle extends Shape { public void draw() { System.out.println("Drawing Circle"); } }
Drawing Rectangle Drawing Circle
请注意,我们在这里将子对象分配给父对象。
Shape s=new Rectangle();
如您所见,我们在子类 Rectangle 和 Circle 中覆盖了绘制方法。JVM在运行时根据对象分配决定它需要调用哪个方法。这就是为什么这被称为Run time polymorphism.
Run time polymorphism
这就是java中的多态性。
原文链接:https://codingdict.com/