Java课后练习:接口:定义圆柱体类Cylinder实现接口Shape

按如下要求编写Java程序:

(1)定义接口Area,里面包含值为3.14的常量PI和抽象方法double area()。

(2)定义接口SetColor,里面包含抽象方法void setColor(String c)。

(3)定义接口Shape,该接口继承了接口Area和SetColor ,新增抽象方法double volume()。

(4)定义圆柱体类Cylinder实现接口Shape :

• 属性

radius: double类型,底圆半径

height: double类型,圆柱体的高

color: String类型,圆柱体颜色

• 方法

实现接口中的抽象函数

Cylinder (double radius, double height):构造函数

toString()方法 :返回圆柱体的描述信息,如“radius=1.0,height=2.0,color is red, volume =6.28, area=3.14”

(5)Main类作为主类要完成测试功能,生成Cylinder对象,调用对象的toString方法,输出对象的描述信息

接口Area:

package sb;

public interface Area 
{
	final double PI= 3.14;
	abstract double area();
}

定义接口SetColor

package sb;

public interface SetColor 
{
	abstract void setColor(String c);
}

定义接口Shape

package sb;

public interface Shape extends SetColor , Area
{
	abstract double volume();
}

定义圆柱体类Cylinder实现接口Shape

package sb;

public class Cylinder implements Shape
{
	private double radius;//底部圆半径
	private double height;
	private String color;
	
	public Cylinder() {};
	public Cylinder(double radius,double height, String color) 
	{
		this.radius=radius;
		this.height=height;
		this.color=color;
		area();
	}

	public void setColor(String c) 
	{
		System.out.println("新设置的颜色是:"+c);
		this.color=c;
	}

	public double area() 
	{
		double area;
		double ZhouChang=Math.sqrt(this.radius/PI);
		return area=ZhouChang*this.height+this.radius*2;
	}

	@Override
	public double volume() 
	{
		double volume;
		return volume=this.radius*this.height;
		
	}
	public String toString()
	{
		return "颜色是:"+color+"\n底部圆面积为:"+radius+"\n高度为:"+height+"\n面积为:"+area()+"\n体积为:"+volume();
	}

}

Main类作为主类要完成测试功能:

package sb;
import java.util.Scanner;
public class Main {

	public static void main(String[] args) 
	{
		Scanner input=new Scanner(System.in);
		System.out.println("请输入圆柱体底面积");
		int radius=input.nextInt();
		System.out.println("请输入圆柱体高");
		int height=input.nextInt();
		System.out.println("请输入圆柱体颜色");
		String color=input.next();
		Cylinder C1=new Cylinder(radius,height,color);
		System.out.println(C1.toString());
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值