1.图形类
package com.yfs.javase; public class Shape { //计算面积方法 public double getArea() { System.out.println("计算面积"); return 0; } }
2.圆
package com.yfs.javase; public class Circle extends Shape { private double r; public Circle(double r) { this.r = r; System.out.println("创建圆形面积"); } public double getArea() {//覆盖父类的方法 System.out.println("计算圆形面积..."); return 3.14 * r * r; } }
3.矩形
package com.yfs.javase; public class Rangton extends Shape { private double width; private double length; public Rangton(double width, double length) { this.width = width; this.length = length; System.out.println("创建矩形面积"); } public double getArea() { System.out.println("计算矩形面积..."); return width * length; } }
4.三角形
package com.yfs.javase; public class Trantangle extends Shape { private double height; private double width; public Trantangle(double height, double width) { this.height = height; this.width = width; System.out.println("创建三角形面积"); } public double getArea() { System.out.println("计算三角形面积..."); return 1.0 / 2 * width * height; } }
5.测试
package com.yfs.javase; import java.util.Random; public class Test1 { /** * 编写一个图形类,提供计算面积的方法。 * 通过继承图形类,封装三角形,圆形,正方形类, * 覆盖父类的方法。在测试类里随机产生10个图形, * 面积求和。 */ public static void main(String[] args) { Shape[] shapes = new Shape[10];//存放子类对象 Random ran = new Random(); double sum = 0; //创建随即图形 for (int i = 0; i < shapes.length; i++) { int r = ran.nextInt(101); if(r > 65) { shapes[i] = new Circle(ran.nextInt(10)); } else if( r > 35 ){ shapes[i] = new Rangton(ran.nextInt(10),ran.nextInt(10)); //shapes[i].setWidth(); } else { shapes[i] = new Trantangle(ran.nextInt(10), ran.nextInt(10)); } } System.out.println("================"); //计算随机图形面积 for (int i = 0; i < shapes.length; i++) { // Circle c = (Circle)shapes[i]; // sum += c.getArea(); sum += shapes[i].getArea();//子类对象计算面积 } System.out.println("sum = " + sum); } }