What are synthetic fields in Java?

Geek picture Geek · Jun 12, 2013 · Viewed 18.7k times · Source

Can someone explain in an easy to understand way the importance of synthetic fields in Java. I recall reading it in context of non static inner classes where each such inner class instance maintains a reference to the enclosing class. Why are such references/fields called synthetic fields?

Answer

NINCOMPOOP picture NINCOMPOOP · Jun 12, 2013

A synthetic field is a compiler-created field that links a local inner class to a block's local variable or reference type parameter. The compiler synthesizes certain hidden fields and methods in order to implement the scoping of names. These fields are private unless noted otherwise, or they are at most of package scope. You can get more information here and in JLS

A class member that does not appear in the source code must be marked using a Synthetic attribute, or else it must have its ACC_SYNTHETIC flag set. The only exceptions to this requirement are compiler-generated methods which are not considered implementation artifacts, namely the instance initialization method representing a default constructor of the Java programming language (ยง2.9), the class initialization method (ยง2.9), and the Enum.values() and Enum.valueOf() methods..