您的位置:首页 > 编程语言 > Java开发

java多态(翻译自Java Tutorials)

2012-11-26 19:29 302 查看
原文出自 http://www.cnblogs.com/ggjucheng/archive/2012/11/26/2789638.html
多态,在字典中的定义是指在生物学的生物体或物种可以有许多不同的形式或阶段。这一原则也适用于面向对象的编程语言如Java语言。子类可以定义自己独特的行为,并共享父类一些相同的功能。

多态可以通过Bicycle类的修改进行展示。例如,可以添加一个printDescription方法,用来显示当前在实例中的所有数据。

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语言多态的特性,我们扩展Bicycle类: MountainBike和RoadBike类.例如MountainBike,添加一个变量suspension,这个是一个字符串,它的值如果是Front指示这个这行车有前减震器,如果是Dual,指示自行车有一前一后减震器。

更新后的类如下:

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信息也会被包含在输出。

下一个,创建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 方法已经被重载,这一次会显示轮胎的宽度。

总结一下:现在有三个类: Bicycle, MountainBike和RoadBike。两个子类重载了printDescription方法并输出唯一信息。

这里是一个测试程序,创建三个Bicycle变量,每个变量赋值给三个bicycle类的每个实例,每个变量都会被输出。

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语言中多态的重要特性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: