通过应用实例讨论Java多态的实现 (二)

2014-11-24 09:53:47 · 作者: · 浏览: 1
shape.computeArea();

63. shape.computeVolume();

64. System.out.println("circle area: " + shape.getArea());

65. System.out.println("circle volume: " + shape.getVolume());

66. //多态调用

67. shape = sphere;

68. shape.computeArea();

69. shape.computeVolume();

70. System.out.println("Sphere area: " + shape.getArea());

71. System.out.println("Sphere volume: " + shape.getVolume());

72. }

73. }


这里对Circle对象多态调用computeVolume()毫无意义,仅是为了演示目的。其运行结果为:

74. circle area: 529.2967869138698

75. circle volume: 0.0

76. Sphere area: 2050.8395382450512

77. Sphere volume: 69865.26693621474


如果需要多态调用大量对象,可以使用数组和循环如下:


78. ...

79. for(int i = 0; i < objNum; i++) { //循环objNum次

80. shape[i].computeArea(); //i从0到objNum-1

81. shape[i].computeVolume();

82. System.out.println("The area: " + shape[i].getArea());

83. System.out.println("The volume: " + shape[i].getVolume());

84. }


这个循环语句也被称为多态管理循环。