※J.Y Chen 的個人部落格 ※

Just Follow Our Heart And We will shine!

117 瀏覽人次

【程式語言】JAVA的第十堂課 |物件導向程式設計(繼承練習題)

Published: in JAVA by .

hw10_41.java (main)

public class hw10_41 {
    public static void main(String[] arsg) {
        CCircle cir1 = new CCircle(5);
        CCircle cir2 = new CCircle(2);
        CSquare squ1 = new CSquare(10);
        CSquare squ2 = new CSquare(5);
        CTraingle tra1 = new CTraingle(2,2);
        CTraingle tra2 = new CTraingle(3,4);
        System.out.println("cir1(5) = " + cir1.area());
        System.out.println("cir2(2) = " + cir2.area());
        System.out.println("squ1(10) = " + squ1.area());
        System.out.println("squ2(5) = " + squ2.area());
        System.out.println("tra1(2,2) = " + tra1.area());
        System.out.println("tra2(3,4) = " + tra2.area());
    
        double[] arr = new double[6];
        arr[0] = cir1.area(); arr[1] = cir2.area(); arr[2] = squ1.area(); arr[3] = squ2.area(); arr[4] = tra1.area(); arr[5] = tra2.area();
        
        System.out.println("MAX_AREA = " + largest(arr));
    }

    public static double largest (double a[]) {
        double max = a[0];
        for (int i = 0 ; i<6 ; i++) {
            if (a[i] > max) {
                max = a[i];
            }
        }
        return max;
    }
}

CSharp.java

public class CSharp {
    public static double pi = 3.14;

    public double area(){
        return 0;
    }
}

CCircle.java

public class CCircle extends CSharp {
    double radius;
    
    CCircle(double r){
        this.radius = r;
    }
    public double area() {
        return radius * radius * pi;
    }
}

CSquare.java


public class CSquare extends CSharp{
    double side;
    CSquare(double s){
        this.side = s;
    }

    public double area(){
        return side*side;
}
}

CTraingle.java

public class CTraingle extends CSharp {
    double bottom , high;
    
    CTraingle(double b , double h) {
        this.bottom = b;
        this.high = h;
    }
    
    public double area(){
        return bottom*high/2;
    }
}

Result:

©2019 - 2024 Henry Chen