什么是我的数组错了

时间:2015-04-23 22:24:45

标签: java arrays

这是一项家庭工作任务,我似乎无法理解为什么它不起作用。

import java.util.ArrayList;

public class Main {
    Shapes[] listTest = new Shapes[6];
    listTest[0] = new Circle[2.0];
    listTest[1] = new Triangle[];
    listTest[2] = new Rectangle[4];
    listTest[3] = new Trap[];
    listTest[4] = new Square[4];
    listTest[5] = new Quadrilateral[];
}

// This is the other class

public class Circle implements Shapes {  

    private double radius;
    private String name = "circle";

    public Circle(double radius){         
        this.radius = radius;    
    }
    public double area (){
        double perimeter = Math.PI*radius*radius;
        return perimeter;
    }
    public double perimeter (){
        double area = Math.PI * 2*radius;
        return area;
    }
    public String getName (){
        return name; 
    }
}

这是包含构造函数和使用私有变量的方法的另一个Circle类。

3 个答案:

答案 0 :(得分:2)

方括号用于初始化数组,我觉得你打算调用Shape对象的构造函数。将这些方括号[]更改为括号()

这是我的意思的一个例子。

public class Main {
    interface Shape {
        // ...
    }

    class Circle implements Shape {
        private double radius;
        public Shape(double radius) {
            this.radius = radius;
        }
    }
    // the rest of the shapes

    public static void main(String[] args) {
        Shape[] listTest = new Shape[6];
        listTest[0] = new Circle(2.0);
        // the rest of the shapes
    }
}

答案 1 :(得分:2)

数组期望Shape Object不是Shapes数组。

例如:

正在寻找

listTest[0] = new Circle(2);

不是

listTest[0] = new Circle[2.0];

答案 2 :(得分:0)

关于如何在java中创建对象。 基于名称:ShapesCircleTriangle。它看起来像Java Inheritance,所以我认为逻辑是声明一个Shapes的数组,然后将instances/objects实例化为数组元素。实例化对象时,必须使用括号()而不是方括号

对Circle,Triangle类使用new运算符时,它被称为instantiation,您在内存中创建了一个对象,调用了该类的构造函数。

参见一些例子:

Point originOne = new Point(23, 94);
Square rectOne = new Square();
Rectangle rectTwo = new Rectangle(50, 100);

回到您的代码,您的Circle类的constructor

public Circle(double radius)
{
this.radius = radius;
}

因此,要创建一个对象,它将是new Circle(2.0)

相关问题