1.
1)定义接口 AreaInterface,该接口有一个双精度浮点型的常量 PI,它的值等于 Math.PI;含
有一个求面积的方法 double area()。
2)定义一个 Rectangle(长方形)实现 AreaInterface 接口,该类有两个 private 访问权限的双
精度浮点型变量 x(长)和 y(宽);定义一个 public 访问权限的构造方法,用来给类变量赋
值;实现 area()方法得到长方形的面积;定义 toString()方法,返回一段字符串信息,内容如
下格式:“该长方形面积为:”+面积。
3)定义一个 TestArea 类,在它的 main()方法中;创建一个 Rectangle 的实例,长为 10.0,宽
为 20.0,输出它的面积。
接口AreaInterface定义
public interface AreaInterface {
double PI = Math.PI;
double area();
}
定义Rectangle(长方形)实现 AreaInterface 接口
public class Rectangle implements AreaInterface {
private double x;
private double y;
public void Retangle(double x, double y){
this.x=x;
this.y=y;
}
@Override
public double area() {
return x*y;
}
public String toString(){
return "该长方形的面积为:"+area();
}
}
定义TestArea 类
public class TestArea {
public static void main(String[] args) {
Rectangle re = new Rectangle();
re.Retangle(10.0,20.0);
System.out.println(re.toString());
}
}
2.定义接口 Shape,其中包括 area 方法。类 Circle、Square 和 Triangle 均实现了接口 Shape。
定义主函数,创建元素个数为 3 的 Shape 类型的一维数组,分别为数组元素创建 Circle、Square
和 Triangle 类型的对象,最后分别调用各数组元素的 area 方法,输出相关信息。
接口 Shape
public interface Shape {
double area();
}
类 Circle
public class Circle implements Shape {
private double r;
public Circle(double r) {
this.r = r;
}
@Override
public double area() {
return Math.PI * r * r;
}
public String toString() {
return "该圆形的面积是:" + area();
}
}
Square
public class Square implements Shape {
private double a;
public Square(double a) {
this.a = a;
}
@Override
public double area() {
return a * a;
}
public String toString() {
return "该正方形的面积是:" + area();
}
}
Triangle
public class Triangle implements Shape {
private double x, y, z;
private double m;
public Triangle(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public double area() {
m = (x + y + z) / 2;
return Math.sqrt(m * (m - x) * (m - y) * (m - z));
}
public String toString() {
return "该三角形的面积是:" + area();
}
}
Main函数
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("输入圆形的半径:");
double r = sc.nextDouble();
System.out.print("输入正方形边长:");
double a = sc.nextDouble();
System.out.print("输入三角形三边:");
double x = sc.nextDouble();
double y = sc.nextDouble();
double z = sc.nextDouble();
Shape sh[] = new Shape[3];
sh[0] = (Shape) new Circle(r);
sh[1] = (Shape) new Square(a);
sh[2] = (Shape) new Triangle(x, y, z);
for (int i = 0; i < sh.length; i++) {
System.out.println(sh[i].toString());
}
}
}