简体   繁体   中英

Why don't we initialize the fields as soon as we declare them?

Why don't we initialize the fields as soon as we declare them in the class? Could the workflow of the code differ if we have initialized the fields as soon as we have declared them? The point is, why we don't initialize them above the constructor?

First of all: we can!

For a more in-depth answer, I will quote The Java Tutorials that says:

However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate.

Therefore, to keep a coherent and homogeneous way of writing the code that ensures the code readability, we tend to avoid initializing some fields directly and some others in the constructor (or elsewhere).

We can initialize a field when it is declared:

class Foo {
   int a = 1;
}

We can initialize a field in a constructor:

class Foo {
   int a;

   Foo() {
     a = 1;
   }
}

We can even initialize a field in an initializer block:

class Foo {
   int a;

   {
     a = 1;
   }
}

Actually, the compiler converts the first and third forms into the second.

(Of course, if the field isn't final , we can also (re)assign it in a method).

If you know the initial value a needs to have when you're writing the code, and it's a simple expression, by all means write it in the first way; it's generally worth avoiding the initializer way (mostly because it's unusual, and not very pretty). And this way is great, if you have multiple constructors, but want to set the same value in all the constructors: the same initialization gets copied into all of the constructors (or, at least, the ones which don't invoke this(...) ).

But if you need to set a based on something like a constructor parameter, you have to do (something like) the second way:

class Foo {
   int a;

   Foo(int a) {
     this.a = a;
   }
}

Which of the approaches you use depends on the situation.

I only initialize final fields, everything else is initialized by constructors.

class MyClass{
    final static int SERIAL = 12345678;

    int a, b, c, d;

    MyClass(int i){
        a = b = c = d = i;
    }

    MyClass(){
        this(1);
    }
}

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