public class Diagram {
//計算面積
public double area(){return 0;}
}
//圓類:繼承圖形類
public class Crile extends Diagram{
private double r;
public Crile(double r){
this.r=r;
}
//重寫area方法
public double area(){
double r=this.r;
return r*r*3.14;
}
}
//三角形類:繼承圖形類
public class Triangle extends Diagram{
private double high; //三角形的高
private double bottom; //三角形的底
public Triangle(double h,double b){
this.high=h;
this.bottom=b;
}
public double area(){
double h=this.high;
double b=this.bottom;
return h*b/2;
}
}
//測試
public class test {
public static void main(String[] args) {
System.out.println("請選擇圖形的類型:(1)三角形(2)圓");
Scanner scanner=new Scanner(System.in);
int i=scanner.nextInt();
if(i==1){
System.out.println("妳選擇的是三角形!請輸入三角形高長(回車結束):");
double high=scanner.nextLong();
System.out.println("請輸入三角形底長(回車結束):");
double bottom=scanner.nextLong();
//這裏體現動態,如果選擇的圖形是三角形,那麽創建三角形類
//調用的時候就是調用的三角形的方法
Diagram diagram=new Triangle(high, bottom);
System.out.println("三角形的面積為:"+diagram.area());
}
if(i==2){
System.out.println("妳選擇的是圓形!請輸入圓的半徑(回車結束):");
double r=scanner.nextLong();
Diagram diagram=new Crile(r);
System.out.println("三角形的面積為:"+diagram.area());
}
}
}
其他的壹樣了,純手工 望采納!