用接口实现计算每个立方体的体积并输出结果的程序(接口及多态性及匿名方法的结合使用)

题目:

有三个立方体,球体,长方体,圆柱体,用接口实现计算每个立方体的体积并输出结果的程序

1.首先是测试类

//package com.Lsheng.java;

import java.util.Scanner;

public class c5_18 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in); //这是为了体验从控制台输入
		double n = sc.nextDouble();
		c5_18 c = new c5_18();
		
		
		Sphere sphere = new Sphere(n); //这是正常的直接调用
		System.out.println("球的体积="+ sphere.volume());
		
		Cuboid cuboid = new Cuboid(15.0,9.0,8.0);//这是体现一下多态的使用,接口也是引用数据类型
		System.out.println("立方体体积" + c.getVolume(cuboid));
		//Cylinder cylinder = new Cylinder(7.0,8.0);
		
		//这里是体验一下匿名方法的使用,也是多态的使用
		System.out.println("圆柱体体积"+c.getVolume(new Cylinder(7.0,8.0)));
	}
	
	public  double getVolume(Solid solid) {
	    return solid.volume();
   }
	//也可以直接一点,比较方便, 静态方法
	//public  static double getVolume(Solid solid) 
   // return solid.volume();

}

2.用到的接口 ,每个需求面积都需要用到的方法

//package com.Lsheng.java;
/*
 * 有三个立方体,球体,长方体,圆柱体,用接口实现计算每个立方体的体积并输出结果的程序
 */

interface Solid{//立方体
	public static final double PI = 3.14159;
	public abstract double volume();
}

//定义球体类
class Sphere implements Solid{
	private double radius;
	
	public Sphere(double r) {
		this.radius = r;
	}
	public double volume() {//重写求体积的方法
		return 4.0/3.0 * PI * Math.pow(radius, 3);
	}
}

3.以及需求面积的类

//package com.Lsheng.java;

public class Cuboid implements Solid{
	private double length, width, height;
	
	public Cuboid(double l, double w, double h) {
		this.length = l; this.width = w; this.height = h;
	}
	
	public double volume() {
		return length*width*height;
	}
	
	
}
package com.Lsheng.java;

public class Cylinder implements Solid{
	private double radius, height;
	
	public Cylinder(double r, double h) {
		this.radius = r; this.height = h;
	}
	public double volume() {
		return PI * radius *radius*height;
	}
	
}

输出结果

 

有疑问留言,谢谢

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值