Description |
先定義一個圓類Circle,有double類型的半徑屬性,有帶參數的構造函數和求面積的computeArea方法(爲保護型的,返回值爲面積,圓周率取3.14); 然後定義一個從Circle派生的圓柱類Cylinder,增加double類型的高屬性,有帶參數的構造函數以及一個計算圓柱體積的成員函數,此函數中要用到從父類繼承來的求面積方法。實現並測試這個類,在main()函數中讀入數據, 然後輸出體積。 要求主函數中必須調用Cylinder的構造函數語句。 |
Input |
第一行輸入數據的組數N, 然後有N組數據。每組數據由兩個整型數組成,一個是半徑,一個是高,數據之間以空格分隔。 |
Output |
輸出圓柱體積(保留2位有效數字)。 |
Sample Input |
2 10 10 20 5 |
Sample Output |
3140.00 |
派生類定義:
class 父類名
{
注意父類中定義的變量要用protected
}
class 子類名 extends 父類名
{
...
}
............................................................................................................................................................
import java.util.*;
class Circle
{
protected double radius;
public Circle(){}
public Circle (double radius)
{
this.radius=radius;
}
}
class Cylinder extends Circle
{
private double height;
public Cylinder(){}
public Cylinder(double radius,double height) //繼承父類的域並初始化;
{
this.radius=radius;
this.height=height;
}
public double computeArea(double radius)
{
return 3.14*radius*radius;
}
public double computeV(double radius,double height)
{
return computeArea(radius)*height;
}
}
public class Main {
public static void main(String args[]){
double r,h;
int t,i;
Scanner cin = new Scanner(System.in);
while(cin.hasNext()){
t=cin.nextInt();
for(i=0;i<t;i++)
{
r=cin.nextDouble();
h=cin.nextDouble();
Cylinder s=new Cylinder(r,h);
System.out.printf("%.2f\n",s.computeV(r, h));
}
}
}
}
測試數據: