"...you can still access the other Beta object through the static variable a2.b1 - because it's static."
The book says that a2.b1 still points to the other Beta object after this code runs, but I don't see that a2.b1 was ever assigned to anything. I think it's actually a1.b1 that still points to the Beta object that was previously referenced by variable b1. Do I have it wrong?
Steve Marriott wrote:but I don't see that a2.b1 was ever assigned to anything. I think it's actually a1.b1 that still points to the Beta object that was previously referenced by variable b1. Do I have it wrong?
Partly.
You are right that no assignments have been made through a1.b1. However, b1 is static. That means that there is one single reference for all instances of class A. Therefore, whatever its value is, a1.b1 == a2.b1, because it's the exact same thing.
Ah yes. I see that now: a1.b1 == a2.b1 Brilliant! Thanks for the response.
Follow up:
static Beta b1;
Is it fair to say that the line above is a static initializer, even though it has no braces as one would find in a 'textbook' static initializer? If that's true, then this helps me to understand even better that this line executes when the JVM loads the Alpha class, not just when the Alpha class is instantiated.
That's not an (static) initializer but a static declaration. As such, it doesn't "do" anything other then inform the compiler and the JVM that it's there.
im i right in saying that although the code 'b1 = null' is executed, it is still accessible as the a2 object still has a reference to b1 because its a static variable?
Also am i right in thinking that b1 would not be eligible for garbage collection until there is no reference to it, ie if 'a2 = null' was executed?
David Houghton wrote:im i right in saying that although the code 'b1 = null' is executed, it is still accessible as the a2 object still has a reference to b1 because its a static variable?
Correct... Setting b1 (the local variable) to null just removes one reference to the object. It is still accessable via the b1 (static variable) of the alpha class.
David Houghton wrote:Also am i right in thinking that b1 would not be eligible for garbage collection until there is no reference to it, ie if 'a2 = null' was executed?
No. Setting a2 to null, will *not* make the b1 (static variable) object eligible. Even if a2 is equal to null, you can access static variables with it, and not get a null pointer exception.
got it, static variables are accessable whether or not a class object has been initialised, or declared for that matter, depending on the access modifiers?
ie method arguments such as 'Color.GRAY'
Post by:autobot
What kind of corn soldier are you? And don't say "kernel" - that's only for this tiny ad:
a bit of art, as a gift, that will fit in a stocking