Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private Final vs Final Private

Tags:

java

android

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!

like image 840
DustNSummers Avatar asked Jun 27 '18 00:06

DustNSummers


People also ask

Is final final private or private Java?

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.

What is the difference between private and private final 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.

Does final go before or after private?

final private and private final are the same thing. The order doesn't matter.

Why do we use private Finals?

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.


1 Answers

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.

like image 150
Andreas Avatar answered Oct 17 '22 19:10

Andreas