java新手筆記16 面積

來源:互聯網
上載者:User

標籤:

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 面積

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.