7-1 jmu-Java-03面向对象基础-04-形状-继承 (15分)
作者:Bright Xu
前言
前面题目形状
中我们看到,为了输出所有形状的周长与面积,需要建立多个数组进行多次循环。这次试验使用继承与多态来改进我们的设计。
本题描述:
- 定义抽象类
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 + ']';
}
}