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
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
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;
}
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