標籤:
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);}}
java新手筆記16 面積