静态对象数组

时间:2012-02-22 08:42:19

标签: java

public class Array                                                               
{
    static String[] a = new String[] {"red", "green", "blue"};
    static Point[] p = new Point[] {new Point(1, 2), "3,4"};

    public static void main(String[] args)
    {
        System.out.println("hello");
    }

    class Point
    {
        int x;
        int y;

        Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        Point(String s)
        {
            String[] a = s.split(",");
            x = a[0].parseInt();
            y = a[1].parseInt();
        }
    }
}

在上面的程序中,静态Point数组初始化失败,报告错误:

Array.java:4: non-static variable this cannot be referenced from a static context
    static Point[] p = new Point[] {new Point(1, 2), "3,4"};  

但是,静态String数组成功了。它们之间有什么区别?

我真的需要一个静态对象数组,因为它很容易引用而不实例化外部类。

谢谢

6 个答案:

答案 0 :(得分:5)

您必须做三件事才能使代码正常工作。我会解释他们。首先看看工作版本。

public class Array {
    static String[] a = new String[]{"red", "green", "blue"};
    static Point[] p = new Point[]{new Point(1, 2), new Point("3,4")};

    public static void main(String[] args) {
        System.out.println("hello");
    }

    static class Point {
        int x;
        int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        Point(String s) {
            String[] a = s.split(",");
            x = Integer.parseInt(a[0]);
            y = Integer.parseInt(a[1]);
        }
    }
}

以下是您必须做出的三项更改。

<强> 1。将"3,4"更改为new Point("3,4")new Point(3,4)

我们知道数组可以容纳相似类型的项目。在这里,您声明了一个名为p的{​​{1}}类型的数组。这意味着它只能包含Point类型的项目(或其子类型)。但是第二个元素Point的类型为"3,4",而且您不匹配。因此,您必须指定Stringnew Point("3,4")才能获取new Point(3,4)类型的项目。

<强> 2。您需要制作Point课程Point

来自Java Tutorial

static

这里你的An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. 类是一个内部类,它必须能够访问Point类的所有成员。为此,Array类的每个对象必须与Point类的对象相关联。但是,您正在创建的数组Array位于p上下文中。因此,您必须将static类设为Point,或将数组static设为非静态类。

第3。 p不是parseInt

的方法

StringparseInt类的静态方法,而不是Integer类的静态方法。因此,您必须将其称为String

希望这会有所帮助:)

答案 1 :(得分:4)

您需要使Point成为静态嵌套类,如下所示:

static class Point {

答案 2 :(得分:1)

Point[]必须是数组或Point "3,4"不是Point的实例 并为此错误使Point类静态

答案 3 :(得分:1)

以下是Oracle Online Reference

的解释
  

内部课程

     

与实例方法和变量一样,内部类是关联的   使用其封闭类的实例并可直接访问它   对象的方法和字段。另外,因为内部阶级是   与实例相关联,它无法定义任何静态成员   本身。

     

作为内部类实例的对象存在于实例中   外类的。请考虑以下类:

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}
  

InnerClass的一个实例只能存在于一个实例中   OuterClass并且可以直接访问其方法和字段   封闭实例。

也无法从封闭类型的静态成员中访问它,因为它需要一个实例存在。

答案 4 :(得分:1)

将您的Point类声明为static:

...
static class Point
{
    ...
}

这是必要的,因为Point是一个内部类(String不是)。

但是,{new Point(1, 2), "3,4"};是您的下一个问题。我想它应该是{new Point(1, 2), Point(3, 4)};

答案 5 :(得分:0)

您可能想要创建Point Static嵌套类。

static class Point {

}

检查this

相关问题