This question has a slight emphasis on Java but applies to any OO language. Is there any reason not to initialize instance variables in their declarations? It seems there are no obvious reasons not to. It minimizes the risk of silly null pointer exception mistakes.
For example:
class MyClass {
private String name = ""; // Initialized here
public MyClass(){
// Something
}
}
But in some text books they don't bother to initialize straight away. What might be a reason to not do so? Does it matter?
One case where it is better not to initialise inline is where you have multiple constructors that initialise fields in different ways. It would be inefficient to initialise your field at the declaration and then replace that value with a value passed to a specific constructor later.