I recently came across a piece of code:
public class SomeClass
{
private Logger logger = LoggerFactory.getInstance().getLogger(SomeClass.class);
private int whatever;
// .. Rest of the class definition
}
And was blown away! This code compiles and runs beautifully! I’ve only seen this kind of assignment performed on class variables (statics). I was under the impression that in order to assign values to instance variables, one had to do so inside of a method. Wrong!
My question: is this a way of overriding the Java default value for types? For instance, in the example above, the 1ogger field would ordinarily be assigned a value of null until assgined a value by a constructor/setter. Other types, such as primitives, all have their own built-in defaults, such as booleans which are by default false.
Is this just Java’s way of letting you override built-in defaults? Otherwise, what the heck is this and why is it compiling?!?
Thanks in advance!
I don’t see anything wrong with it. The declaration can include an assignment, and that’s what you are doing – assigning an initial value to your field.
You can give initial values to your fields in many ways: via constructor, via an initializer block (
{..}) or by assigning the values directly, as you did.See the Initializing Fields section of the tutorial.