谁能提供一个简单的示例来说明Java中动态和静态多态性之间的区别?
多态性
1.静态绑定/编译时绑定/早期绑定/方法重载。(在同一类中)
2.动态绑定/运行时绑定/后期绑定/方法重写(在不同的类中)
重载示例:
class Calculation { void sum(int a,int b){System.out.println(a+b);} void sum(int a,int b,int c){System.out.println(a+b+c);} public static void main(String args[]) { Calculation obj=new Calculation(); obj.sum(10,10,10); // 30 obj.sum(20,20); //40 } }
首要示例:
class Animal { public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); } } public class TestDog { public static void main(String args[]) { Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();//output: Animals can move b.move();//output:Dogs can walk and run } }