在OOP編程語言中,多態是繼數據抽象和繼承以後的第三種基本特徵。java
動態綁定(後期綁定/運行時綁定):在運行時根據對象的類型進行綁定。也就是編譯器一直不知道對象的類型,但方法調用機制能找到正確的方法體並加以調用。draw()方法的全部調用都是經過動態綁定進行的,由隨機產生幾何形狀能夠看出,編譯器事先不知道哪些對象會調用draw(),都是在運行時動態綁定的。編程
package Eight; import java.util.Random; class Shape{ public void draw(){ System.out.println("Shape draw"); } public void out(){ System.out.println("Shape"); } } class Circle extends Shape{ public void draw(){ System.out.println("Circle draw"); } public void out(){ System.out.println("Circle"); } } class Square extends Shape{ public void draw(){ System.out.println("Square draw"); } public void out(){ System.out.println("Square"); } } class RandomShapeGenerator{ private Random random = new Random(47); public Shape next(){ switch(random.nextInt(3)){ default: case 0: return new Circle(); case 1: return new Square(); } } } public class Shapes { private static RandomShapeGenerator gen = new RandomShapeGenerator(); public static void main(String[] args){ Shape[] s = new Shape[4]; for(int i=0;i<s.length;i++){ s[i] = gen.next(); } for(Shape sp:s){ sp.draw(); sp.out(); } } } /*Circle draw 動態綁定 Circle draw Square draw Circle draw*/ /*添加out方法後 * Circle draw Circle Circle draw Circle Square draw Square Circle draw Circle*/
協變返回類型:即在子類的覆蓋方法中能夠返回父類方法中的返回類型的的子類類型。dom
class Base{ public Object OverrideredFunction(){ return new Object(); } } class Inherit extends Base{ //String是Object的子類,因此能夠這麼寫 @Override public String OverrideredFunction(){ //這裏return父類方法的返回類型Object的子類類型String return "Nice!"; } }