Documentation

The Java™ Tutorials
Hide TOC
Polymorphism多态性
Trail: Learning the Java Language
Lesson: Interfaces and Inheritance
Section: Inheritance

Polymorphism多态性

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. 字典对多态性的定义是指生物学中的一个原则,即一个有机体或物种可以有许多不同的形式或阶段。This principle can also be applied to object-oriented programming and languages like the Java language. 这一原则也可以应用于面向对象编程和Java语言等语言。Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.一个类的子类可以定义它们自己独特的行为,同时还可以共享父类的一些相同功能。

Polymorphism can be demonstrated with a minor modification to the Bicycle class. 多态性可以通过对Bicycle类的轻微修改来演示。For example, a printDescription method could be added to the class that displays all the data currently stored in an instance.例如,可以将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 + ". ");
}

To demonstrate polymorphic features in the Java language, extend the Bicycle class with a MountainBike and a RoadBike class. 要演示Java语言中的多态特性,请使用MountainBike类和RoadBike类扩展Bicycle类。For MountainBike, add a field for suspension, which is a String value that indicates if the bike has a front shock absorber, Front. Or, the bike has a front and back shock absorber, Dual.对于MountainBike,为suspension添加一个字段,该字段是一个String值,指示自行车具有前减震器(Front)或是具有前后减震器(Dual)。

Here is the updated class:以下是更新的类:

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.");
    }
}

Note the overridden printDescription method. 请注意被重写的printDescription方法。In addition to the information provided before, additional data about the suspension is included to the output.除了前面提供的信息外,输出中还包括有关悬架的附加数据。

Next, create the RoadBike class. 接下来,创建RoadBike类。Because road or racing bikes have skinny tires, add an attribute to track the tire width. 由于公路自行车或赛车的轮胎很薄,请添加一个属性来跟踪轮胎宽度。Here is the RoadBike class:以下是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.");
    }
}

Note that once again, the printDescription method has been overridden. 请注意,printDescription方法再次被覆盖。This time, information about the tire width is displayed.这一次,将显示有关轮胎宽度的信息。

To summarize, there are three classes: Bicycle, MountainBike, and RoadBike. 总而言之,有三类:BicycleMountainBikeRoadBikeThe two subclasses override the printDescription method and print unique information.这两个子类覆盖printDescription方法并打印唯一信息。

Here is a test program that creates three Bicycle variables. 下面是一个测试程序,创建了三个Bicycle变量。Each variable is assigned to one of the three bicycle classes. 每个变量分配给三个自行车类别中的一个。Each variable is then printed.然后打印每个变量。

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();
  }
}

The following is the output from the test program:以下是测试程序的输出:

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.

The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. Java虚拟机(JVM)为每个变量中引用的对象调用适当的方法。It does not call the method that is defined by the variable's type. 它不调用由变量类型定义的方法。This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.这种行为称为虚拟方法调用,它展示了Java语言中重要多态性特性的一个方面。


Previous page: Overriding and Hiding Methods
Next page: Hiding Fields