package ex1;
import java.util.Scanner;
class Circle{
private double radius = 0;
public Circle() {
}
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return radius*radius*Math.PI;
}
}
class Trapezoid{
private double length1 = 0;
private double length2 = 0;
private double high = 0;
public Trapezoid() {
}
public Trapezoid(double length1, double length2, double high){
this.length1 = length1;
this.length2 = length2;
this.high = high;
}
public double getArea() {
return (length1+length2)*high/2;
}
}
public class Test {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("-----Class Circle Test-----");
System.out.println("Please input the radius:");
double radius = stdIn.nextDouble();
Circle[] circleTest = new Circle[2];
circleTest[0] = new Circle();
circleTest[1] = new Circle(radius);
System.out.println("The area of the circle1 is: " + circleTest[0].getArea());
System.out.println("The area of the circle2 is: " + circleTest[1].getArea());
System.out.println("-----Class Trapezoid Test-----");
System.out.println("Please input the length1, length2, high in order:");
double[] a = new double[3];
for(int i=0; i<a.length; i++) {
a[i] = stdIn.nextDouble();
}
Trapezoid trapezoidTest = new Trapezoid(a[0], a[1], a[2]);
System.out.printf("The area of the Trapezozid is: %.2f", trapezoidTest.getArea());
}
}
运行结果
更新
四种实现方式
1.
package ex1; //第一次试验
import java.util.Scanner;
//继承实现
//抽象类Shape
abstract class Shape{
abstract public double getArea();
}
//Circle继承Shape
class Circle extends Shape{
private double radius =