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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的程序中,静态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"};
Run Code Online (Sandbox Code Playgroud)
但是,静态String
数组成功了.他们之间有什么区别?
我真的需要一个静态对象数组,因为它很容易引用而不实例化外部类.
谢谢
您必须做三件事才能使代码正常工作.我会解释他们.首先看工作版.
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]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
以下是您必须进行的三项更改.
1.改变"3,4"
到new Point("3,4")
或new Point(3,4)
我们知道数组可以容纳相似类型的项目.在这里,您将声明一个名为p
type 的数组Point
.这意味着它只能包含类型的项Point
(或其子类型).但第二个元素"3,4"
是类型String
,你有不匹配.因此,您必须指定new Point("3,4")
或new Point(3,4)
获取类型的项目Point
.
你需要Point
上课static
从Java教程:
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.
Run Code Online (Sandbox Code Playgroud)
这里你的Point
类是一个内部类,它必须能够访问Array
类的所有成员.为此,Point
类的每个对象必须与类的对象相关联Array
.但是,p
您正在创建的数组是在static
上下文中.因此,您必须使Point
该类成为static
一个或使该数组p
成为非静态数组.
3. parseInt
不是一种String
阶级方法
parseInt
是Integer
类的静态方法而不是String
类.所以你必须这样称呼它Integer.parseInt(stringValue)
.
希望这可以帮助 :)