tags:

views:

47

answers:

2

Hi, A couple of questions

  1. 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?

  2. If I have

    public 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

+1  A: 

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.

Donnie
'Initialization occurs before the constructor is entered'. No it doesn't. It occurs after the implicit or explicit super() call and before the next line of code in the constructor.
EJP
+1  A: 

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.

Gunslinger47