多態性的字典定義是指生物學中的原理,其中生物體或物種能夠具備許多不一樣的形式或階段,這個原則也能夠應用於面向對象的編程和像Java語言之類的語言,類的子類能夠定義它們本身的惟一行爲,但仍然共享父類的一些相同功能。編程
能夠經過對Bicycle
類的微小修改來演示多態性,例如,能夠將printDescription
方法添加到顯示當前存儲在實例中的全部數據的類中。segmentfault
public void printDescription(){ System.out.println("\nBike is " + "in gear " + this.gear + " with a cadence of " + this.cadence + " and travelling at a speed of " + this.speed + ". "); }
要演示Java語言中的多態特性,請使用MountainBike
和RoadBike
類擴展Bicycle
類,對於MountainBike
,添加一個suspension
字段,這是一個字符串值,表示自行車是否有前減震器,或者,自行車有一個先後減震器。測試
這是更新的類:this
public class MountainBike extends Bicycle { private String suspension; public MountainBike( int startCadence, int startSpeed, int startGear, String suspensionType){ super(startCadence, startSpeed, startGear); this.setSuspension(suspensionType); } public String getSuspension(){ return this.suspension; } public void setSuspension(String suspensionType) { this.suspension = suspensionType; } public void printDescription() { super.printDescription(); System.out.println("The " + "MountainBike has a" + getSuspension() + " suspension."); } }
請注意重寫的printDescription
方法,除了以前提供的信息以外,還有關於suspension
的其餘數據包含在輸出中。code
接下來,建立RoadBike
類,由於公路車或賽車的輪胎很薄,因此添加一個屬性來跟蹤輪胎的寬度,這是RoadBike
類:對象
public class RoadBike extends Bicycle{ // In millimeters (mm) private int tireWidth; public RoadBike(int startCadence, int startSpeed, int startGear, int newTireWidth){ super(startCadence, startSpeed, startGear); this.setTireWidth(newTireWidth); } public int getTireWidth(){ return this.tireWidth; } public void setTireWidth(int newTireWidth){ this.tireWidth = newTireWidth; } public void printDescription(){ super.printDescription(); System.out.println("The RoadBike" + " has " + getTireWidth() + " MM tires."); } }
請注意,再次重寫了printDescription
方法,此次,顯示有關輪胎寬度的信息。ip
總而言之,有三個類:Bicycle
、MountainBike
和RoadBike
,這兩個子類重寫printDescription
方法並打印惟一信息。字符串
這是一個建立三個Bicycle
變量的測試程序,每一個變量都分配給三個自行車類別中的一個,而後打印每一個變量。get
public class TestBikes { public static void main(String[] args){ Bicycle bike01, bike02, bike03; bike01 = new Bicycle(20, 10, 1); bike02 = new MountainBike(20, 10, 5, "Dual"); bike03 = new RoadBike(40, 20, 8, 23); bike01.printDescription(); bike02.printDescription(); bike03.printDescription(); } }
如下是測試程序的輸出:虛擬機
Bike is in gear 1 with a cadence of 20 and travelling at a speed of 10. Bike is in gear 5 with a cadence of 20 and travelling at a speed of 10. The MountainBike has a Dual suspension. Bike is in gear 8 with a cadence of 40 and travelling at a speed of 20. The RoadBike has 23 MM tires.
Java虛擬機(JVM)爲每一個變量中引用的對象調用適當的方法,它不會調用由變量類型定義的方法,此行爲稱爲虛方法調用,並演示Java語言中重要多態特徵的一個方面。