When I write a class in Java, I like to initialize the attributes which are set to a default value directly and attributes which are set by the caller in the constructor, something like this:
public class Stack<E> {
private List<E> list;
private int size = 0;
public Stack(int initialCapacity) {
list = new ArrayList<E>(initialCapacity);
}
// remainder omitted
}
Now suppose I have a Tree class:
public class Tree<E> {
private Node<E> root = null;
// no constructor needed, remainder omitted
}
Shall I set the root attribute to null, to mark that it is set to null by default, or omit the null value?
EDIT:
I came up with that idea after reading the sources of LinkedList and ArrayList, which both clearly set their attributes (size in LinkedList and firstIndex/lastIndex in ArrayList) to 0.
There is no need to explicitly initialize a reference-typed attribute to
null. It will be initialized to null by default. Similarly, there are default initialization rules for the primitive types:false, andchar),floatanddoubleattributes are all initialized to zero.So the initialization of
sizein the example is also strictly unnecessary.It is therefore purely a matter of style as to whether you do or do not initialize them. My personal opinion is that it does not improve readability, and therefore is a waste of time. (I don’t write my code to be maintained by people who don’t understand the basics of Java …)