Java Recap: Initialization, Static and Default Constructor

Overview

This is a quick recap about Java initialization of static fields and the usage of constructor, note the behavior of default constructor differs from C++.

Java Initialization of Static Fields

In Java, you cannot apply the static keyword to local variables, so it only applies to fields. But like in C, you can declare a local variable in function as static, and this variable is initialized once and this static variable will stay around until the whole program exists.

Java Constructor, A Way to Guaranteed Initialization

One of the “unsafe” programming is about non-initialized variable, and this is addressed by guaranteed initialization with the constructor which both C++ and Java support. But there are differences of the default constructor in C++ and Java.

In Java, different from C++, the javac will not generate a default constructor for you (once you declared any constructors with non-empty arguments). That is, consider a Tree class, if Tree(int) is your only constructor, then the compiler won’t let you create a Tree object any other way. The following Java code demonstrate this

public class Tester {
    public static void main(String[] args) {
        Tree tree = new Tree(10);    // OK, correct
        // Tree tree2 = new Tree();  // javac compile error: cannot find the symbol: constructor Tree()
        // Tree tree2 = new Tree;    // javac compile error: need '(' or '[' after Tree
        Dog dog = new Dog();         // OK, correct
        System.out.println("Hello Java!");
    }
}

class Tree {
    private int height;
    Tree(int i) {
        height = i;
    }
}

class Dog {
    private String name;
}

And note from the above code, we should always associate the ‘()’ when we create an object like the Tree() in the above example, but in C++, it is valid to write it as: Tree *ptr = new Tree; which is a statement calling the default constructor and the syntax even allow to eliminate the ‘()’. To summarize, two key facts about Java constructor need to be kept in out mind;

  • Java won’t generate default constructor (constructor with empty arguments) for you, you have to define it explicitly, to make it more accurate, if you do not declare any constructors in your code, there is a default one, because otherwise, you will not even be able to create that object. As long as you defined any constructors with non-empty arguments, then you have to declare the default constructor explicitly if you want to create an object simply as new Tree().
  • In Java, when you create a new object by new statement, the parentheses are required to be associate with the Class name.

Summary

This is a quick recap about Java initialization of static fields and the usage of constructor, note the behavior of default constructor differs from C++.

Written on December 5, 2014