在练习多态数组时,遇到一个问题:
我定义了大小为4的数组,但是存入的元素会有一个为0,找不到问题出在哪,麻烦各位看看
最后结果为:
代码如下:
public class GraphicTest {
public static void main(String[] args) {
Graphic[] arr = new Graphic[4];
Rectangle r1 = new Rectangle();
r1.setLength(5);
r1.setWidth(2);
arr[0] = r1;
Rectangle r2 = new Rectangle();
r2.setLength(4);
r2.setWidth(3);
arr[1] = r2;
Circle c1 = new Circle();
c1.setRadius(2);
arr[2] = c1;
Circle c2 = new Circle();
c1.setRadius(1);
arr[3] = c2;
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].getInfo());
}
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length-i; j++) {
if(arr[j].area()>arr[j+1].area()){
Graphic tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].getInfo());
}
}
}
public class Circle extends Graphic {
private double radius;
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI*radius*radius;
}
@Override
public double perimeter() {
return Math.PI*radius*2;
}
@Override
public String getInfo() {
return "半径为:"+radius+super.getInfo();
}
}
public class Rectangle extends Graphic{
private double length;
private double width;
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
@Override
public double area() {
return length*width;
}
@Override
public double perimeter() {
return (length+width)*2;
}
@Override
public String getInfo() {
return "长"+length+"宽"+width+super.getInfo();
}
}
public class Graphic {
public double area(){
return 0.0;
}
public double perimeter(){
return 0.0;
}
public String getInfo(){
return "面积:"+area()+"周长:"+perimeter();
}
}