加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 静态对象数组

发布时间:2020-12-14 05:47:08 所属栏目:Java 来源:网络整理
导读: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(
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 {

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读