java实验:创建一个接口Shape,类Circle、Rectangle实现area方法, Star类另有一返回值boolean型的方法isStar


/*创建一个接口Shape,其中有抽象方法area,
 * 类Circle、Rectangle实现area方法计算其面积并返回,
 * 又有Star类实现Shape的area方法,其返回值是0,
 * Star类另有一返回值boolean型的方法isStar;
 * 在main方法中创建一个数组,根据随机数向其中加入Shape的不同子类对象,
 * 然后将数组元素依次取出,判断其是否为Star类,如是返回其个数,否则返回其面积。*/

interface Shape {
	public abstract double area();
}

class Circle implements Shape {
	double r;

	public Circle() {
	}

	public Circle(double r) {
		this.r = r;
	}

	public double area() {
		return Math.PI * r * r;
	}

}

class Rectangle implements Shape {
	double h, w;

	public Rectangle() {
	}

	public Rectangle(double h, double w) {
		this.h = h;
		this.w = w;
	}

	public double area() {
		return h * w;
	}

}

class Star implements Shape {

	public double area() {
		return 0;
	}

	public static boolean isStar(Shape sh) {
		return sh instanceof Star;
	}
}

public class Csj14 {
	public static void main(String[] args) {
		Shape[] sh = new Shape[10];
		for (int i = 0; i < sh.length; i++) {
			int a = (int) (Math.random() * 10);// 生成[0,10]区间的整数
// m+(int)(Math.random()*n) 语句可以获取 m~m+n 的随机数,所以 2+(int)(Math. random()*(102-2)) 表达式可以求出 2~100 的随机数
			if (a < 2) {
				sh[i] = new Circle(a);
			} else if (a < 7) {
				sh[i] = new Rectangle(a, a);
			} else {
				sh[i] = new Star();
			}
		}
		int num = 0;
		for (int i = 0; i < sh.length; i++) {
			if (Star.isStar(sh[i])) {
				System.out.println("is Star,num:" + ++num);
			} else {
				System.out.println("not Star,area:" + sh[i].area());
			}
		}
	}
}

你可能感兴趣的:(java,java)