5

I have a private final field in one class and then I want to address that field in a subclass. I want to change field access/visibility modifier from private to protected, so I don't have to call getField() method from subclass and I can instead address that field directly (which is more clear and cohessive). Will there be any side effects or complications if I change private to protected for a final field?

UPDATE: from logical point of view, it's obvious that descendant should be able to directly access all predecessor fields, right? But there are certain constraints that are imposed on private final fields by JVM, like 100% initialization guarantee after construction phase(useful for concurrency) and so on. So I would like to know, by changing from private to protected, won't that or any other constraints be compromised?

2 Answers 2

7

I think you are referring to the "freeze of final fields" on successful object instantiation:

When a constructor terminates normally, the thread performs freeze actions on all final fields defined in that class.

as stated in http://www.cs.umd.edu/~pugh/java/memoryModel/semantics.pdf

I guess this is a confusing subject, Alex Miller (former colleague at Terracotta), wrote up on it here : http://tech.puredanger.com/2008/11/26/jmm-and-final-field-freeze/

Anyways, I guess what I'm trying to say is that freeze happens on all final fields, not only private final ones... At least that's my understanding of JMM. And of such, have coded to that and haven't been proven wrong... until now ! ;)

4

According to section 17.5 of the JLS, final fields have the same Java Memory Model semantics regardless of access. In fact, there are no private fields in the code examples from that section. They all have default access.

Just keep in mind the rules laid out in the JLS: all bets are off if you allow another thread to see a reference to your object before all of the constructors have completed.

Also, there are two gotchas for calling overridable methods from the superclass constructor: the overriden method in the subclass will see default values for fields (even final ones) that haven't been written yet, and they also might publish a reference to the partly-constructed instance. These caveats should be documented both on the constructor and on the methods that the constructor might invoke. Or better yet, don't call overridable methods from the constructor in the first place.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.