非静态变量,这不能从静态上下文引用 - 为什么在这里?

时间:2011-11-26 19:40:48

标签: java static compiler-errors

我有一个代码:

package why;

public class Foo
{
    public class Foo1
    {
        String bar;

        public Foo1(String bar)
        {
            this.bar = bar;
        }

        public static Foo1 MYCONSTANT = new Foo(null);
    }

}

为什么我得到'非静态变量,这不能从静态上下文引用'? 我分配了非静态类的实例。

为什么在这里?

public static Foo getMYCONSTANT()
{
    return new Foo(null, null);
}

谢谢

2 个答案:

答案 0 :(得分:6)

让我们看看这个例子:

public class MainClass {

  public class NonStaticClass {

    public static NonStaticClass nonStatic = new NonStaticClass();
    //Compile error: The field nonStatic cannot be declared static; 
    //static fields can only be declared in static or top level types
    public static int i = 10;//this field also causes the same compile error
  }

}

问题是NonStaticClass是,不是静态的。非静态内部类不能包含静态字段。

如果你想在内部类中有一个静态字段,你需要使类静态。

来自java文档:

  

内部课程

     

与实例方法和变量一样,内部类是关联的   使用其封闭类的实例并可直接访问它   对象的方法和字段。另外,因为内部类是   与实例相关联,它无法定义任何静态成员   本身

有关详细信息,请查看Nested Classes

答案 1 :(得分:1)

我不确定你真正的问题是什么......但也许这可能会有所帮助:

  

http://en.wikipedia.org/wiki/Singleton_pattern

     

在他的书“有效Java”的第二版中,Joshua Bloch声称   “单元素枚举类型是实现a的最佳方式   对于任何支持枚举的Java,单例“[9]。枚举的使用是   非常容易实现,并且没有关于可序列化的缺点   对象,必须以其他方式规避。

public enum Singleton {
        INSTANCE;
}