Did a few searched on the inter-webs and could not find an easy answer for this. My problem set is using Java within the Android Framework, but I believe this is just standard Java behavior as well. I understand the definitions of final
and private
, both used for variable access and modifiers. I was following some code and tutorials when the instructions asked me to initialize a variable as a final private
variable. Not having seen this before, I instead made a private final
variable. Later on, the code asked me to initialize the variable in a constructor, which obviously fails against a private final
variable as it is immutable. HOWEVER, it did not fail when I changed the variable to a final private
... which made me interested. Does anyone have ideas why this is the case?
Thanks for the responses!
The main difference between private and final keywords in Java is that private is primarily an access modifier, which controls the visibility of variables, methods, and classes in Java applications, while final is just a modifier that enforces additional constraints on the field, method, and class in Java.
private is about accessibility like public or protected or no modifier. final is about modification during inheritance. private methods are not just accessible from the outside of the class. final methods can not be overridden by the child class.
final private and private final are the same thing. The order doesn't matter.
private static final will be considered as constant and the constant can be accessed within this class only. Since, the keyword static included, the value will be constant for all the objects of the class. private final variable value will be like constant per object. You can refer the java.
The Java Language Specification, section 8.3.1. Field Modifiers, says:
FieldModifier: (one of) Annotation public protected private static final transient volatile
If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.
Which means that private final
is the preferred style, but it's exactly the same as final private
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With