题目: 编写接口Shape,包含一个用于计算几何体表面积的area()方法; 然后创建立方体类、长方体类、和圆柱类,分别实现Shape接口中的方法。最后创建一个测试类。创建立方体类、长方体类和圆柱类的实例对象,并计算其表面积。
完整代码如下
package JavaTextFour.Ex4455;
import java.util.Scanner;
interface Shape{
float area();
}
class Cube implements Shape{
private float Cublength;
Cube(){}
Cube(float l){
Cublength=l;
}
@Override
public float area() {
return Cublength*Cublength*6;
}
}
class Rectangle implements Shape{
private float Reclength;
private float Recwide;
private float Rechigh;
Rectangle(){}
Rectangle(float l,float w,float h){
Reclength=l;
Recwide=w;
Rechigh=h;
}
@Override
public float area() {
return (Reclength*Recwide+Reclength*Rechigh+Recwide*Rechigh)*2;
}
}
class Cylindrical implements Shape{
private final float PI=3.14f;
private float Cylradius;
private float Cylhigh;
Cylindrical(){}
Cylindrical(float r,float h){
Cylradius=r;
Cylhigh=h;
}
@Override
public float area() {
return PI*Cylradius*Cylradius*2+2*PI*Cylradius*Cylhigh;
}
}
public class ShapeText {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Shape shape=null;
System.out.println("请输入立方体的棱长:");
float Cublength=sc.nextFloat();
shape=new Cube(Cublength);
System.out.println("棱长为"+Cublength+"的立方体的表面积为:"+shape.area());
System.out.println("请输入长方体的长:");
float Reclength=sc.nextFloat();
System.out.println("请输入长方体的宽:");
float Recwide=sc.nextFloat();
System.out.println("请输入长方体的高:");
float Rechigh=sc.nextFloat();
shape=new Rectangle(Reclength,Recwide,Rechigh);
System.out.println("长为"+Reclength+"宽为"+Recwide+"高为"+Rechigh+"的长方体的表面积为:"+shape.area());
System.out.println("请输入圆柱体的底面半径:");
float Cylradius=sc.nextFloat();
System.out.println("请输入圆柱体的高:");
float Cylhigh=sc.nextFloat();
shape=new Cylindrical(Cylradius,Cylhigh);
System.out.println("底面半径为"+Cylradius+"高为"+Cylhigh+"的圆柱体的表面积为:"+shape.area());
sc.close();
}
}