抽象类:Shape


public abstract class Shape {

    protected double c;
    public abstract double area();
}

类Square正方形,继承抽象类

public class Square extends Shape{
    public Square(double c){
        this.c = c;
    }
    /*
     * 计算正方形的面积
     */
    public double area(){
        return 0.0625*c*c;
    }

}

类Circle 圆形,继承抽象类

public class Circle extends Shape {
    
    public Circle(double c){
        this.c = c;
    }
    /*
     * 计算圆形面积
     */
    public double area(){
        return 0.0796*c*c;
    }

}

测试类


public class TestShape {
    public static void main(String[] args){
        Shape[] shapes = new Shape[2];
        shapes[0] = new Circle(4);//数组中的第一个元素为圆形。周长为4
        shapes[1] = new Square(4);//数组中的第二个元素为正方形,周长为4
        maxArea(shapes);
    }
    public static void maxArea(Shape[] shapes){
        double max = shapes[0].area();
        int maxIndex = 0;
        for(int i = 1;i<shapes.length;i++){
            double area = shapes[i].area();
            if(area>max){
                max = area;
                maxIndex = i;
            }
        }
        System.out.println("数组索引为:"+maxIndex+"的图形的面积最大,面积为:"+max);
    }

}

 

posted on 2017-06-01 09:56  两枝梅  阅读(503)  评论(0编辑  收藏  举报