求图形的最大面积
/**
* 声明一个数组,包含各种图形对象,获取最大面积
*/
public class TestShap {
public static void main(String[] args) {
Shap[] shaps = new Shap[4];
shaps[0]=new Square(1);
shaps[1]=new Square(2);
shaps[2]=new Circle(1);
shaps[3]=new Circle(2);
maxArea(shaps);
}
//主类中没有成员变量,用静态方法
public static void maxArea(Shap[] shaps){
int maxIndex=0;
double maxArea=shaps[0].area();
for(int i=1;i<shaps.length;i++){//次数从1开始比较
if(maxArea<shaps[i].area()){
maxArea=shaps[i].area();
maxIndex=i;
}
}
System.out.println("面积的最大值为:"+maxArea+" 索引为:"+maxIndex);
}
}
abstract class Shap{
protected double c;
abstract double area();
}
class Square extends Shap{
public Square(double c){
super();
this.c=c;
}
double area(){
return 0.0625*c*c;
}
}
class Circle extends Shap{
public Circle(double c){
super();
this.c=c;
}
double area(){
return 0.0796*c*c;
}
}
面积的最大值为:0.3184 索引为:3