(1)設計一個形狀類 Shape,包含一個 getArea()方法,該方法不包含實際陳述句。 (2)在 Shape 類基礎上設計圓形、矩形、三角形和梯形四個子類,要求根據實 際形狀重寫 getArea()方法。 (3)設計一個 TestShape 類,包含變數 area(存盤總面積)、靜態方法 countArea(Shapes),該方法負責把引數中的形狀面積加入到 area 中。在 main 方 法中新建(2)中四種型別的物件 shape1、shape2、shape3、shape4,通過呼叫 countArea 方法把四個物件面積累加到 area 中,最后輸出 area。
這個TestShape類和主函式怎么寫啊?
uj5u.com熱心網友回復:
public class TestShape {
public static void main(String[] args) {
Shape shape1 = new Circle(10);
Shape shape2 = new Rectangle(5,10);
Shape shape3 = new Triangle(1,2,3); // a, b, c
Shape shape4 = new Trapezoid(3, 5, 4); // a, b, h
double area = countArea(shape1, shape2, shape3, shape4);
System.out.println(area);
}
private static double countArea(Shape...shapes) {
double area = 0.0;
for (Shape shape : shapes) area += shape.getArea();
return area;
}
}
abstract class Shape {
public abstract double getArea();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......
值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......