IAmYourFaja
IAmYourFaja

Reputation: 56894

Java Non-Static Field Defaults?

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!

Upvotes: 0

Views: 454

Answers (3)

Slash
Slash

Reputation: 506

The built-in defaults cannot be overriden, int fields are initialized to zero for instance. You can do nothing about that (apart from initializing the field to other value yourself)

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499730

You can't change the default value for a type, but you can write to instance variables in:

  • Field declarations:

    private int x = 10;
    
  • Constructors:

    private int x;
    public Foo() {
        x = 10;
    }
    
  • Instance initializers:

    private int x;
    
    void someOtherMethod() {}
    
    // These are relatively rare
    {
        x = 10;
    }
    
  • Normal methods:

    private int x;
    
    void someMethod() {
        x = 10;
    }
    

See section 8.3.2.2 of the JLS for more on initializers for instance variables, as well as section 8.3 of the JLS for more general syntax of field declaration.

Upvotes: 1

Bozho
Bozho

Reputation: 597016

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.

Upvotes: 2

Related Questions