C
C
cypok2012-05-11 16:53:44
Java
cypok, 2012-05-11 16:53:44

Why is declaring class initialized and not referencing?

Hello, I have a question here for the sake of general development: can anyone explain why when accessing static members of a class, the initialization of the class in which the member is declared is called, and not the one we are accessing?

Here is what the JVM Specification (§5.5) says:

Upon execution of a getstatic , putstatic , or invokestatic instruction, the class or interface that declared the resolved field or method is initialized if it has not been initialized already.

The following example confirms this and outputs 37 (the initializer is Barnot called at all):
class Foo {
    public static int x;

    static {
        x = 37;
    }
}

class Bar extends Foo {
    static {
        x = 42;
    }
}

public class test {
    public static void main(String args[]) {
        System.out.println(Bar.x);
    }
}

Those. interesting motivation, why is it done so?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
gricom, 2012-05-11
@gricom

Because the static field "x" is defined in class Foo. It is not in the Bar class, it can only look at it and give you the result, so the static block in Bar is not executed (because there was no call to the class, in fact there was only a call to Foo).

B
barker, 2012-05-11
@barker

Why should it work the way you expect? It would be very strange. Static methods and fields are not redefined in any way, the call does not go through the usual invoke *, but based on the data that was at the time of COMPILATION. Roughly speaking, this is a class field, not a class object.

L
leventov, 2012-05-11
@leventov

There is no option to call only the static block Bar - that is, either we initialize only the declaration place, or the entire chain from the declaration place to the class we are referring to. Although, as barker noted , the JVM will not understand that there .x was taken through a dot to Bar, this information is not in the bytecode.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question