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,4"};
但是,静态String数组成功.他们之间有什么区别?
我真的需要一个静态对象数组,因为它很容易引用而不实例化外部类.
谢谢
解决方法
你需要使Point成为一个静态嵌套类,如下所示:
static class Point {