A couple of questions
If I declare a variable in a class, class A, as
private int blah = myclass.func();
When is the func() actually called? The first time class A is initiated?
If I have
publi开发者_运维问答c final int blah = myclass.func();
I know that somehow blah is dynamically updated (e.g. everytime I call some other function in class A, I always get an updated value of blah - which was obtained by calling myclass.func())... but I don't know why. Would someone explain this behavior?
Thanks, Mike
You're acting like blah
is static
.
When is the func() actually called? The first time class A is initiated?
Each time class A is instantiated
everytime I call some other function in class A, I always get an updated value of blah
There exists one blah
for every instance (object) of class A. The method func()
will be called and its value assigned to each new instance of blah
every time you say new A()
. Each time it appears that blah
is updated, it's because you're looking at a completely different object than last time.
These are instance initializers. See 8.3.2 in the java spec, and pages 4 & 5 of this article. Initialization occurs before the constructor is entered, and there are caveats with forward references and uninitialized variable usage that you should be aware of if you try to do fancy stuff (the previously linked article talks about them in some depth).
An initializer is executed exactly once when the object is constructed, so I'm not sure what you're talking about with the 2nd half of your question.
精彩评论