7.30 Java interface实现多态

import javax.jws.Oneway;

interface Shape{
	double Getc();
	double Gets();
}

class Circle implements Shape{
	private double radius;
	public Circle() {
		this(0.0);
	}
	public Circle(double radius) {
		this.radius = radius;
	}
	public double Getc() {
		double c = 2.0 * Math.PI * radius;
		return c;
	}
	public double Gets() {
		double s = Math.PI * radius * radius;
		return s;
	}
	@Override
	public String toString() {
		return "[Circle] : radius = " + radius; 
	}
}

class Rectangle implements Shape{
	private double len;
	public Rectangle() {
		this(0.0);
	}
	public Rectangle(double len) {
		this.len = len;
	}
	public double Getc() {
		double c = 4.0 * len;
		return c;
	}
	public double Gets() {
		double s = len * len;
		return s;
	}
	@Override
	public String toString() {
		return "[Rectangle] : Side_Length = " + len;
	}
}

public class Mine {
	public static double cal(Shape shape[]) {
		double tot_sum = 0.0;
		for(Shape itShape : shape) {
			tot_sum += itShape.Gets();
			System.out.println(itShape);
		}
		return tot_sum;
	}
	public static void main(String[] args) {
		Shape[] shape = new Shape[5];
		for(int i = 0 ; i < shape.length ; i++) {
			double d = Math.random();
			if(d > 0.5)shape[i] = new Circle(Math.random());
			else shape[i] = new Rectangle(Math.random());
		}
		double tot_sum = cal(shape);
		System.out.println("Tot_Sum = " + tot_sum);
 	}
}
posted @ 2023-07-30 20:34  N0zoM1z0  阅读(5)  评论(0编辑  收藏  举报