7.29 Java
熟悉掌握Java的语法 提高编程能力
package duotai;
import javax.xml.stream.events.Namespace;
abstract class Shape {
public abstract double Getc();
public abstract double Gets();
}
class Circle extends Shape{
private double radius;
public Circle(){
this(0.0);// 等价于 this.radius = radius
}
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
@Override
public double Gets() {
double s = Math.PI * radius * radius;
return s;
}
@Override
public double Getc() {
double c = 2.0 * Math.PI * radius;
return c;
}
@Override
public String toString(){
return "[Circle] radius = " + radius;
}
}
class Rectangle extends Shape{
private double len;
public Rectangle() {
this(0.0);
}
public Rectangle(double len) {
this.len = len;
}
@Override
public double Gets() {
double s = len * len;
return s;
}
@Override
public double Getc() {
double c = 4.0 * len;
return c;
}
@Override
public String toString() {
return "[Rectangle] Side Length= " + len;
}
}
public class Duotai {
public static double Cal(Shape[] shapes) {
double s = 0.0;
for(Shape shape : shapes) {
System.out.println(shape);
s += shape.Gets();
}
return s;
}
public static void main(String[] args) {
Shape[] shapes = new Shape[5];
for(int i = 0; i < shapes.length; i++) {
double d = Math.random();
if(d < 0.5)shapes[i] = new Circle(1);
else shapes[i] = new Rectangle(2);
}
double tot_s = Cal(shapes);
System.out.println("tot sum = "+tot_s);
}
}