0

Suppose I have the following code:

public class Everything{
    public static int answer = 42;

    public int getAnswer(){
        return this.answer;
    }
}

Technically-speaking, this.answer doesn't actually exist, but the compiler lets us off with a warning. Why don't we get a compile error instead?

CodeBlind
  • 4,519
  • 1
  • 24
  • 36
  • Your IDE will most likely show a warning. *Static member accessed via instance reference* or something similar. – maba May 29 '13 at 22:25
  • They're compilable because the spec says it is permitted. What other reason could there be? – dlev May 29 '13 at 22:28

2 Answers2

3

this is a valid reference to an instance of Everything. As such, it is a valid reference to the Everything class, and therefore a valid way of accessing any static member and/or method of that class.

You can even do:

Everything nothing = null;
nothing.answer; // Does not throw an NPE!!

Generally, this is not very good practice... IDEA, for instance, will warn you that you "access a static member via an instance reference".

fge
  • 119,121
  • 33
  • 254
  • 329
  • I definitely agree that no one should ever write code like that. I guess I just always thought of an instance of a class and the class itself as entirely different constructs. It seems really weird to me that the lines between class and class instance are allowed to be blurred, but only when arguably terrible code is written. – CodeBlind May 29 '13 at 22:36
  • @BenLawry Contrast this behavior with C#, where calling a static method on an instance variable is a compile-time error. – dlev Jun 08 '13 at 07:11
0

when the Everything class is loaded all the static blocks and static variables are executed/initialized in the order they appear. So any further reference to static variables will refer to those. It doesn´t matter if they are accessed from the same class, using the class name or an instance. (or even a null reference as fge points out)

jambriz
  • 1,273
  • 1
  • 10
  • 25