简体   繁体   中英

Need for initializing final reference within parameterized constructor(s) in Java

import java.util.*;

public Class C
{
     final Vector v;
     C()
     {
          v=new Vector();
     }

     C(int i)
     {
          //Here, it is an error. v might not have been initialized.
     }

     public void someMethod()
     {
           System.out.println(v.isEmpty());
     }

     public static void main(String[] args)
     {
          C c=new C();
          c.someMethod();
     }
} 

The Above code is a compile time error. I know but it says( in NetBeans) variable v should be initialized. When I initialized it in the overloaded constructor it fixes the problem and prints "true". My problem is why should I initialize it again in the overloaded version of constructors.(I have initialized it once in the default constructor ) and I'm not even using the overloaded version. Why?

Because the overloaded constructor does not invoke the default one.

Use this() to invoke it.

When you create a new object, only one of the constructors of your class is called to initialize the object. You seem to think that all of the constructors are called, or that the default (no-arguments) constructor is always called. That is not the case.

So, each constructor needs to initialize all the final member variables.

Note that from one constructor you can explicitly call another one using this(...) . For example, as the first line of your C(int i) constructor, you could add a line: this(); to call the C() constructor. Another solution is to initialize the member variable at the line where you declare it:

public class C {
    // v will be initialized, no matter which constructor will be used
    final Vector v = new Vector();

    C() {
    }

    C(int i) {
        // ...
    }

    // ... etc.
}

Note that you don't need to explicitly initialize non- final member variables; if you don't initialize those, Java will initialize them with a default value (which is null for non-primitive type variables). However, you do need to explicitly initialize final member variables.

Another note: Vector is a legacy collection class. You should prefer using ArrayList instead.

Third note: Use generics to make your code more type-safe. For example, if you need to store strings in a list, use ArrayList<String> instead of the raw type ArrayList .

Overloaded constructor does not call the other version unless you explicitly do it with

this();

That's probably what you want to do.

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