0

Lets say I have the following code in front of me:

public class Theory {

public static void main(String[] args) {
        new Theory().program();
    }

void program(){
A.a = A.b;             //won't compile
A.a = new A().b;    

A.b = A.a;             // won't compile either
new A().b = A.a

}

static class A{
    static int a;
    int b;
  }
}

When I hover the mouse over the code it says "non static field cannot be referenced from a static context", which I sort of understand, but I can't wrap my head around why the consecutive line doesn't show a compiler error?

  • There is no thing named `A.b`. `b` is non-static, so the only way you can get to one is `someInstanceOfACreatedWithNew . b ` In other words ... please research what it *actually* means when you add *static* to the definition of an inner class. – GhostCat Oct 27 '20 at 15:01

2 Answers2

0
    A.a = A.b;           // You can't reference an instance field (b) statically
    A.a = new A().b;     // You create an instance of A, use it to access 'b' and assign
                         // it to 'a' which you can access statically.  This is okay.                      

    A.b = A.a;           // You can't reference an instance field (b) statically
    new A().b = A.a;     // This works, but the instance is gone (not 
                         // assigned anywhere) once the assignment is complete.
 
    
    static class A {
        static int a;
        int b;
    }

Note. Don't be confused by the static class declaration. All that means is that the nested class may be instantiated without requiring an instance of the enclosing class. It does not mean that its fields or methods are automatically accessible statically.

WJS
  • 36,363
  • 4
  • 24
  • 39
0

What you are looking at is more like a "tooltip" generated by your IDE since mouse hover over is an IDE function and has nothing to do with the compiler. The message shown compleatly depends on the IDE and probably would change if you change your IDE.
The compilers error you will only see once you actually try to compile the code.

The reason why neither of those two lines would compile is because in every case you are trying to access an instance bound field without and instance, aka "A.b".
The other two lines compile because in both cases you create a new instance of the class and access the instance bound field through it, aka new A().b <- new A() creates the instance

Basti
  • 1,117
  • 12
  • 32