编写接口Shape,包含一个用于计算几何体表面积的area()方法;然后创建立方体类、长方体类、和圆柱类,分别实现Shape接口中的方法。最后创建一个测试类。创建立方体类、长方体类和圆柱类的实例对象

题目: 编写接口Shape,包含一个用于计算几何体表面积的area()方法; 然后创建立方体类、长方体类、和圆柱类,分别实现Shape接口中的方法。最后创建一个测试类。创建立方体类、长方体类和圆柱类的实例对象,并计算其表面积。

完整代码如下

/**
 * @author 昆石
 *编写接口Shape,包含一个用于计算几何体表面积的area()方法;
 *然后创建立方体类、长方体类、和圆柱类,分别实现Shape接口中的方法。
 *最后创建一个测试类。创建立方体类、长方体类和圆柱类的实例对象,并计算其表面积。
 */
package JavaTextFour.Ex4455;
import java.util.Scanner;

//Shape接口
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();
	}

}

发布了13 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44079145/article/details/105457879