Here’s a simple class with a constructor:
//: initialization/SimpleConstructor.java // Demonstration of a simple constructor. class Rock { Rock() { // This is the constructor System.out.print("Rock "); } } public class SimpleConstructor { public static void main(String[] args) { for(int i = 0; i < 10; i++) new Rock(); } } /* Output: Rock Rock Rock Rock Rock Rock Rock Rock Rock Rock *///:~
Now, when an object is created:
new Rock();
storage is allocated and the constructor is called. It is guaranteed that the object will be properly initialized before you can get your hands on it.
Note that the coding style of making the first letter of all methods lowercase does not apply to constructors, since the name of the constructor must match the name of the class exactly.
A constructor that takes no arguments is called the default constructor. The Java documents typically use the term no-arg constructor, but “default constructor” has been in use for many years before Java appeared, so I will tend to use that. But like any method, the constructor can also have arguments to allow you to specify how an object is created. The preceding example can easily be changed so the constructor takes an argument:
[Thinking in Java, 108]