The labs on this site need JavaScript to run. The same content is written out below.
Fundamentals › Java
What is a constructor, and when does it run?
Why it exists — If a constructor takes no values, you have to create an object with new and then fill in the fields one line at a time, and even if you miss one line, the compiler does not tell you, so an object whose name is null gets used as it is. A constructor receives the values that are absolutely needed at the moment the object is created and fills in the fields, and if you write only a constructor that takes values, it blocks creating an object without those values.
Where it's used today — Classes that Java provides, such as new ArrayList<>() and new StringBuilder("start"), also decide the starting state of an object with a constructor. A field that must not change after the object is made is declared final and filled in once in the constructor. In Spring, a common approach is for a class to receive the other objects it needs through the parameters of its constructor.
A constructor is a block of code that you write inside a class. It differs from a method in two ways: its name is the same as the class name, and you do not write a return type. You have to call a method by name to run it, but a constructor runs once every time new Card("Alice") is executed, and it fills in the fields of the object that was just created (Card is a class made as an example for this lab). If you write no constructor at all, the compiler adds one that does nothing. In this lab you remove the Card(String owner) constructor or change the line that creates the object to new Card(), and the same code is compiled and run each time. You see what the compiler reports and how many times the constructor runs.
Checked against real execution · Eight combinations were compiled with javax.tools and run on JDK 21, and the results were checked against the model
class Card {
String owner;
// Constructor: has the same name as the class. It runs when new Card(...) is executed
Card(String owner) {
System.out.println("constructor ran");
this.owner = owner;
}
}
public class Main {
public static void main(String[] args) {
Card a = new Card("Alice");
System.out.println(a.owner);
}
}
The compiler and runtime are JDK 21.0.12.1 (javac 21). For all eight combinations, the same source as the code on the screen (identical line by line) was compiled with javax.tools. The ones that compiled had their class files loaded by a new class loader and Main.main was run, and the results were checked against the standard output that was captured. What was checked is whether compilation succeeded, the diagnostic code of the first error (compiler.err.cant.apply.symbol), the required arguments and the passed arguments named in its message (shown on the screen as the two error descriptions), the number of errors and the lines where they occurred, whether the Main class file was created, the output when run, and the number of "constructor ran" lines counted in that output. For the combinations without a constructor, there is no constructor we wrote, so the number of runs is recorded as 0. The facts that the step sentences rely on were also checked by separate runs. The class file of a Card with no constructor contains one constructor with no parameters. A Card with a constructor that takes a value contains only that constructor. When the constructor body starts, the owner of the new object is already null and the parameter holds the value that was passed. The next line of main runs only after new has finished. A line that calls the constructor by name, such as a.Card("Bob") or Card("Bob"), was a compile-time error (cannot find symbol). The documentation checked was the Java Language Specification (Java SE 21), opened with WebFetch. The rule that the name of a constructor must be the same as the simple name of the class, that it has no return type unlike a method, and that it cannot be called by a method invocation expression follows section 8.8. The rule that a default constructor with no parameters is implicitly declared only for a class that declares no constructor follows section 8.8.9. The rule that the constructor matching the passed arguments is chosen at compile time, and that it is a compile-time error if none matches, follows section 15.9.3. The rule that at run time the object is created, its fields are set to their default values, the arguments are evaluated, and then the constructor is run follows section 15.9.4. The rule that this inside a constructor means the object being created follows section 15.8.3. The kind of error, the number of errors, and the line where each occurs are not set by the specification. They were observed with this javac. When there are several errors, javac reports all of them, but the table shows only the first. When compilation fails, the Main class file was never created, so the table says it cannot run. The code on the screen has the Card class as package-private and has the shape that needs no import line. Having several constructors (overloading), calling another constructor with this(...), the superclass constructor super(...), and the order in which field initializers and the constructor run are not covered in this lab. They are covered in "In-depth lab: Classes, objects, and constructors".
Struck-through text was removed from the first version of the code; highlighted text was added.