//比較三個面積的大小,因為CShapehw10_11 s[]陣列是在static類別裡宣告
//所以void前面必須加static
public static void largest(CShapehw10_11 s[])
{
double max=0.0;
for(int i=0;i<s.length;i++){
if(s[i].area()>max){ //s[i].area()==>呼叫出每個陣列的面積
max=s[i].area();
}
}
System.out.println("面積最大的是"+max);
}
}
class CCirclehw10_11 extends CShapehw10_11 //子類別 CCirclehw10_11
{
private double pi;
private double radius;
public CCirclehw10_11(double p ,double r){ /子類別CCirclehw10_11建構元
pi=p;
radius=r;
}
public double area(){
return pi*radius*radius; //傳回圓面積
}
}
class CSquarehw10_11 extends CShapehw10_11 //子類別 CSquarehw10_11
{
private double length;
private double width;
public CSquarehw10_11(double l ,double w){//子類別CSquarehw10_11建構元
length=l;
width=w;
}
public double area(){
return length*width; //傳回正方形面積
}
}
class CTrianglehw10_11 extends CShapehw10_11 //子類別CTrianglehw10_11
{
private double base=4.0;
private double height=10.0;
public CTrianglehw10_11(double b ,double h){ //子類別CTrianglehw10_11建構元
base=b;
height=h;
}
public double area() {
return (base*height)/2; //傳回三角形面積
}
}
public class hw10_11
{
public static void main(String args[]){
//CCirclehw10_11 cir=new CCirclehw10_11(3.0,4.0);
//cir.area();
//CSquarehw10_11 cqr=new CSquarehw10_11(5.0,6.0);
/cqr.area();
//CTrianglehw10_11 ctr=new CTrianglehw10_11(7.0,8.0);
//ctr.area();
//透過父類別變數存取子類別物件的成員
CShapehw10_11 shp[]=new CShapehw10_11[3];
//傳值到CCirclehw10_11(double p ,double r)建構元,並將回傳面積儲存在shp[0]
shp[0]=new CCirclehw10_11(3.0, 4.0);
System.out.println("圓形面積="+shp[0].area());
//傳值到CSquarehw10_11(double l ,double w)建構元,並將回傳面積儲存在shp[1]
shp[1]=new CSquarehw10_11(5.0,6.0);
System.out.println("正方形面積="+shp[1].area());
//傳值到CTrianglehw10_11(double b ,double h)建構元,並將回傳面積儲存在shp[2]
shp[2]=new CTrianglehw10_11(7.0,8.0);
System.out.println("三角形面積="+shp[2].area());
CShapehw10_11.largest(shp);//將陣列傳遞到largest()函數內比較大小
}
}
沒有留言:
張貼留言