7-1 jmu-Java-03面向對象基礎-04-形狀-繼承 (15分)
前言
前面題目形狀
中我們看到,爲了輸出所有形狀的周長與面積,需要建立多個數組進行多次循環。這次試驗使用繼承與多態來改進我們的設計。
本題描述:
- 定義抽象類
Shape
屬性: 不可變靜態常量double PI
,值爲3.14
,
抽象方法:public double getPerimeter()
,public double getArea()
Rectangle
與Circle
類均繼承自Shape類。
Rectangle類(屬性: int width,length)、Circle類(屬性: int radius)。
帶參構造函數爲Rectangle(int width,int length)
,Circle(int radius)
。
toString
方法(Eclipse自動生成)- 編寫
double sumAllArea
方法計算並返回傳入的形狀數組中所有對象的面積和與
double sumAllPerimeter
方法計算並返回傳入的形狀數組中所有對象的周長和。 - main方法
4.1 輸入整型值n,然後建立n個不同的形狀。如果輸入rect,則依次輸入寬、長。如果輸入cir,則輸入半徑。
4.2 然後輸出所有的形狀的周長之和,面積之和。並將所有的形狀信息以樣例的格式輸出。 提示: 使用Arrays.toString
。
4.3 最後輸出每個形狀的類型與父類型.使用類似shape.getClass()
//獲得類型,shape.getClass().getSuperclass()
//獲得父類型;
注意: 處理輸入的時候使用混合使用nextInt
與nextLine
需注意行尾回車換行問題。
思考
- 你覺得sumAllArea和sumAllPerimeter方法放在哪個類中更合適?
- 是否應該聲明爲static?
輸入樣例:
4
rect
3 1
rect
1 5
cir
1
cir
2
輸出樣例:
38.84
23.700000000000003
[Rectangle [width=3, length=1], Rectangle [width=1, length=5], Circle [radius=1], Circle [radius=2]]
class Rectangle,class Shape
class Rectangle,class Shape
class Circle,class Shape
class Circle,class Shape
參考答案
import java.util.Scanner;
public class Main {
/**
* @author 徐亮亮
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Shape[] shape = new Shape[n];
for (int i = 0; i < n; i++) {
String type = in.next();
if (type.equals("rect")) {
int width, length;
width = in.nextInt();
length = in.nextInt();
shape[i] = new Rectangle(width, length);
}
else if (type.equals("cir")) {
int radius = in.nextInt();
shape[i] = new Circle(radius);
}
}
System.out.println(sumAllPerimeter(shape));
System.out.println(sumAllArea(shape));
String temp = "[";
for (int i = 0; i < n; i++) {
temp += shape[i];
temp += (i < n-1) ? ", " : "]";
}
System.out.println(temp);
for (Shape i : shape) {
System.out.println(i.getClass()+","+i.getClass().getSuperclass());
}
}
static double sumAllPerimeter(Shape[] shape) {
double sum = 0.0;
for (Shape i : shape) {
sum += i.getPerimeter();
}
return sum;
}
static double sumAllArea(Shape[] shape) {
double sum = 0.0;
for (Shape i : shape) {
sum += i.getArea();
}
return sum;
}
}
abstract class Shape{
final static double PI = 3.14;
public abstract double getPerimeter();
public abstract double getArea();
}
class Rectangle extends Shape{
int width, length;
public Rectangle(int width,int length) {
this.width = width;
this.length = length;
}
@Override
public double getPerimeter() {
return 2.0 *(width+length);
}
@Override
public double getArea() {
return width*length;
}
@Override
public String toString() {
return "Rectangle [" + "width=" + width + ", length=" + length + ']';
}
}
class Circle extends Shape{
int radius;
public Circle(int radius) {
this.radius = radius;
}
@Override
public double getPerimeter() {
return PI * radius * 2;
}
@Override
public double getArea() {
return PI * radius * radius;
}
@Override
public String toString() {
return "Circle [" + "radius=" + radius + ']';
}
}