Java – Why use the javadoc parameterless constructor?

Why use the javadoc parameterless constructor?… here is a solution to the problem.

Why use the javadoc parameterless constructor?

In Article 56 of Effective Java (Third Edition), Joshua Bloch states, “Public classes should not use the default constructor because they cannot be documented.”

The default constructor doesn’t do anything unexpected, though, it just creates a new instance. What kind of information should be documented in the documentation comments for the parameterless constructor, and not just in the class comments?

I can understand this if a class has interesting behavior in initializing blocks (otherwise there is nowhere to annotate these), or even non-standard field assignments (possibly calling methods to get initial values). But for most classes, this doesn’t seem to add much. Is there anything I’m missing?

Solution

In most cases you are right.
And I think it makes sense to use the default constructor in these cases because you don’t need to log anything.

There are now some other situations where the record method does, as well as a more specific default state, useful.

Because even if the body of the default constructor is empty, it may use default values in its fields, which can be interesting for records.

Here are two examples of JDK classes where javadoc might bring useful information to constructors with empty bodies.

Stack

/**
 * Creates an empty Stack.
 */
public Stack() {
}

Of course, customers may guess that Stack is empty when calling this constructor, but it would be better to specify it explicitly.

Atomic integers

Take the AtomicInteger empty constructor:

/**
 * Creates a new AtomicInteger with initial value {@code 0}.
 */
public AtomicInteger() {
}

The AtomicInteger constructor is overloaded. So we’re not in the potential default constructor case.
But in any case, it is an empty argument constructor with an empty body, similar to the result produced by the default constructor.

Without these constructors, javadocs, clients of these classes should look at the implementation to guess information, and the API that restricts clients from viewing the implementation to understand its specification is not a well-designed API.

Related Problems and Solutions