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();
}
}
}
In the above program, the static Point
array initialization fails, reporting error:
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"};
But, the static String
array succeeds. What's the difference between them?
I really need a static object array, because it's easy to refer to without instantiate the outer class.
Thanks
Best Answer
You have to do three things to make your code to work. I will explain them . First see the working version.
The following are the three changes you have to make.
1. change
"3,4"
tonew Point("3,4")
ornew Point(3,4)
We know that an array can hold items of similar types. Here you are declaring an array named
p
of typePoint
. That means it can contain item of typePoint
only(or its subtypes). But the second element"3,4"
is of typeString
and you have a mismatch. So you must specify eithernew Point("3,4")
ornew Point(3,4)
to get items of typePoint
.2. You need to make your
Point
classstatic
From Java Tutorial:
Here your
Point
class is an inner class and it must have given access to all the members ofArray
class. For that, each object ofPoint
class must associated to an object ofArray
class. But, the arrayp
you are creating is instatic
context. So, you have to either make thePoint
class astatic
one or make the arrayp
a non-static one.3.
parseInt
is not a method ofString
classparseInt
is a static method ofInteger
class and not ofString
class. So you must call it likeInteger.parseInt(stringValue)
.Hope this helps :)