JAva初心者ノート16面積
2362 ワード
1.グラフィッククラス
2.円
3.長方形
4.三角形
5.テスト
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);
}
}