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?
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
finalmember variables.Note that from one constructor you can explicitly call another one using
this(...). For example, as the first line of yourC(int i)constructor, you could add a line:this();to call theC()constructor. Another solution is to initialize the member variable at the line where you declare it:Note that you don’t need to explicitly initialize non-
finalmember variables; if you don’t initialize those, Java will initialize them with a default value (which isnullfor non-primitive type variables). However, you do need to explicitly initializefinalmember variables.Another note:
Vectoris a legacy collection class. You should prefer usingArrayListinstead.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 typeArrayList.