按要求編寫Java程式---圓柱體計算
阿新 • • 發佈:2018-11-07
1. 題目描述
(1)定義介面A,裡面包含值為3.14的常量PI和抽象方法double area()。
(2)定義介面B,裡面包含抽象方法void setColor(String c)。
(3)定義介面C,該介面繼承了介面A和B,裡面包含抽象方法void volume()。
(4)定義圓柱體類Cylinder實現介面C,該類中包含三個成員變數:底圓半徑radius、
圓柱體的高height、顏色color。
(5)建立主類來測試類Cylinder。
2. 程式碼實現
//(1)定義介面A,裡面包含值為3.14的常量PI和抽象方法double area()。
interface A{
double PI = 3.14;
double area();
}
//(2)定義介面B,裡面包含抽象方法void setColor(String c)。
interface B{
void setColor(String c);
}
//(3)定義介面C,該介面繼承了介面A和B,裡面包含抽象方法void volume()。
interface C extends A, B{
void volume();
}
//(4)定義圓柱體類Cylinder實現介面C,該類中包含三個成員變數:
//底圓半徑radius、 圓柱體的高height、顏色color。
class Cylinder implements C{
private int radius; // 底圓半徑
private int height; // 高
private String color; // 顏色
// 建構函式
public Cylinder(int radius, int height, String color)
{
this.radius = radius;
this.height = height;
this.color = color;
}
// 圓柱體的表面積
public double area()
{
return (PI * radius * radius * 2) + (2 * PI * radius * height);
}
// 圓柱體表面顏色
public void setColor(String c)
{
this.color = c;
// 下面一句話知乎是為了測試使用
System.out.println(this.color);
}
// 圓柱體體積
public void volume()
{
System.out.println(PI * radius * radius * height);
}
}
//(5)建立主類來測試類Cylinder。
public class Test03{
public static void main(String[] args){
Cylinder cl = new Cylinder(2, 2, "紅色");
System.out.println(cl.area());
cl.setColor("綠色");
cl.volume();
}
}
執行結果: