Java – static object array

public class Array                                                               
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 initialization of static point array failed, and the error is reported:

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

However, the static string array succeeded What's the difference between them?

I really need a static object array because it's easy to reference without instantiating a foreign class

thank you

Solution

You need to make point a static nested class, as follows:

static class Point {
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>