Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the Java compiler (specifically its parser) able to understand this statement

Tags:

java

I have the following two classes (in two separate files).

public class Foo
{
    public static class A
    {
        public static final boolean FLAG = false;
    }

    public final A A = new A();
}


public class Bar
{
    void method()
    {
         if (Foo.A.FLAG)  <<<< this is giving "Cannot make static ref to non-static field
            // do something
           ;
    }
}

My question is, why isn't the compiler able to recorgnise that by Foo.A, I meant the class A, not the member, which also happens to be named A?

like image 227
One Two Three Avatar asked Dec 16 '13 21:12

One Two Three


2 Answers

This is called obscuring, an obscure feature/limitation of Java

A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type, or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. Thus, it is may sometimes be impossible to refer to a visible type or package declaration via its simple name. We say that such a declaration is obscured.

If the variable A was static, it would compile since you can can access static members on object references.


Also FLAG hasn't been initialized.

like image 144
Sotirios Delimanolis Avatar answered Oct 24 '22 12:10

Sotirios Delimanolis


Some ways to access the flag:

<Foo_A extends Foo.A> void test1()
{
    if(Foo_A.FLAG)
        ;
}

void test2()
{
    class Foo_A extends Foo.A{}
    if(Foo_A.FLAG)
        ;
}

-------------------------------------
import pkg.Foo.A;

public class Bar
{
    void test3()
    {
        if(A.FLAG)
            ;
    }
}

in these contexts, "Foo.A" can only be interpreted as a type, not a variable.

like image 43
ZhongYu Avatar answered Oct 24 '22 12:10

ZhongYu