简体   繁体   中英

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!

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM