Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-static variable this cannot be referenced from a static context - why here?

I have a code:

package why;

public class Foo
{
    public class Foo1
    {
        String bar;

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

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

}

Why do I get 'non-static variable this cannot be referenced from a static context'? I allocate the instance of non-static class.

Why even here?

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

Thank you

like image 216
user1067230 Avatar asked Nov 26 '11 19:11

user1067230


2 Answers

Lets take a look at this example:

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
  }

}

The problem is that NonStaticClass is, well, not static. A non static inner class can't contain static fields.

If you want to have a static field in the inner class you need to make the class static.

From the java documentation:

Inner Classes

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

For more information take a look at Nested Classes

like image 182
Liviu T. Avatar answered Sep 18 '22 12:09

Liviu T.


I'm not sure what your real question is ... but perhaps this might help:

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

In the second edition of his book "Effective Java" Joshua Bloch claims that "a single-element enum type is the best way to implement a singleton"[9] for any Java that supports enums. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.

public enum Singleton {
        INSTANCE;
}
like image 27
paulsm4 Avatar answered Sep 18 '22 12:09

paulsm4