A non-static variable that 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 am I getting a "non-stationary variable that cannot be referenced from a static context"? I allocate an instance of a non-static class.

Why even here?

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

thanks

+6
source share
2 answers

Let's 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 , well, is not static . A non-stationary inner class cannot 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 this methods and object fields. Also , because the inner class is associated with an instance, it cannot define any static members of itself .

For more information, see Nested Classes

+6
source

I'm not sure what your real question is ... but maybe this can help:

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

In the second edition of his book Effective Java, Joshua Bloch states that "a singleton enumeration type is the best way to implement a singleton" [9] for any Java that supports enums. Using an enumeration is very simple to implement and has no drawbacks regarding serializable objects, which must be bypassed in other ways.

 public enum Singleton { INSTANCE; } 
+1
source

Source: https://habr.com/ru/post/902459/


All Articles