Why no public constructor for Optional in java?

From Joshua Bloch effective Java, Chapter 2. Creating and Destroying
Objects, 1 Item:

Consider static factory methods instead of constructors

Why?

One advantage of static factory methods is that, unlike constructors,
they have names.

With static factory methods we can specify some instantiation behavior in the method definition. This makes the API easier to use and we prevent clients from calling wrong constructors.

For instance here: In Optional.ofNullable -> we allow null value be passed to instantiate the Optional, in Optional.of null value is not allowed and throw exception. We could not use the constructor here.

private Optional(T value) {
    this.value = Objects.requireNonNull(value); //this throws NullPointerException
}
public static <T> Optional<T> of(T value) {
        return new Optional<>(value);
}
public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
} 

Another advantage (already mentioned):

A second advantage of static factory methods is that, unlike
constructors, they are not required to create a new object each time
they’re invoked.

In Optional, the empty value is instantiated just once, and then stored in the static field, this value is reused always when the program needs an empty value.

private static final Optional<?> EMPTY = new Optional<>(); //instantiate value when program starts

public static<T> Optional<T> empty() {
    @SuppressWarnings("unchecked")
    Optional<T> t = (Optional<T>) EMPTY; //return stored value when requested
    return t;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)