1. 程式人生 > >【java學習記錄】2.定義一個計算矩形面積、立方體和球體體積的類,該類完成計算的方法用靜態方法實現

【java學習記錄】2.定義一個計算矩形面積、立方體和球體體積的類,該類完成計算的方法用靜態方法實現

area_volume類(計算矩形面積和立方體體積)

public class area_volume {

double length,width,heigth;//長:length,寬:width,高:heigth

area_volume(double length,double width,double heigth){//初始化
this.length=length;
this.width=width;
this.heigth=heigth;
}

area_volume(){}

double area(){//求矩形面積
double b;
b=length*width;
return b;
}

double volume(){//求立方體體積
double b;
b=length*width*heigth;
return b;
}

}

circular 類(計算球體體積)

public class circular {
double r;
circular(double r){
this.r=r;
}

double volume(){//求球的體積
double v;
double PI=3.14;
v=3*r*r*r*PI/4;

return v;
}

}

test測試類

public class test {
public static void main(String[] args){
area_volume a1=new area_volume(2,5,0);//矩形
area_volume a2=new area_volume(2,5,5);//立方體
circular c=new circular(2);//球

double a3=a1.area();//求a1的面積
double a4=a2.volume();//求a2的體積
double c2=c.volume();//求c的體積

System.out.println("矩形al:"+"\n"+"長:"+a1.length+" "+"寬:"+a1.width+"\n"+"面積為:"+a3+"\n");
System.out.println("立方體a2:"+"\n"+"長:"+a2.length+" "+"寬:"+a2.width+"高:"+a2.heigth+"\n"+"體積為:"+a4+"\n");
System.out.println("球c:"+"\n"+"半徑:"+c.r+"\n"+"體積為:"+c2+"\n");
}
}