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
You have to do three things to make your code to work. I will explain them . First see the working version.
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]);
}
}
}
The following are the three changes you have to make.
1. change "3,4"
to new Point("3,4")
or new Point(3,4)
We know that an array can hold items of similar types. Here you are declaring an array named p
of type Point
. That means it can contain item of type Point
only(or its subtypes). But the second element "3,4"
is of type String
and you have a mismatch. So you must specify either new Point("3,4")
or new Point(3,4)
to get items of type Point
.
2. You need to make your Point
class static
From Java Tutorial:
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.
Here your Point
class is an inner class and it must have given access to all the members of Array
class. For that, each object of Point
class must associated to an object of Array
class. But, the array p
you are creating is in static
context. So, you have to either make the Point
class a static
one or make the array p
a non-static one.
3. parseInt
is not a method of String
class
parseInt
is a static method of Integer
class and not of String
class. So you must call it like Integer.parseInt(stringValue)
.
Hope this helps :)
You'd need to make Point
a static nested class, like this:
static class Point {
Point[]
must be array or Point
"3,4"
is not instance of Point
and make Point class static for this error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With