U
U
username52021-01-18 19:43:27
Java
username5, 2021-01-18 19:43:27

Why is a constructor in a wrapper class deprecated with JDK9?

Hello, I'm reading Schildt's book on Java.
Question on wrapper classes, quote:


The Character( ) constructor has the following form: Character (char character)
But as of JDK9, the Character class constructor is no longer recommended. The current recommendation for obtaining a Character object is to use the static valueOf( ) method. This method returns an object of type Character that encloses the character value ch of the primitive type char

A similar valueOf( ) method is used for other wrappers: Byte, Short, Integer, Long, Float, Double.
Question: why with JDK9 it is not recommended to use a constructor, but change it to a method?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-01-18
@username5

Modern architectural principles favor factory methods. Good manners dictate that a constructor does nothing but initialize fields. A factory method, on the other hand, can do a lot of additional operations, such as interning. A factory method can perform instance-level operations, such as returning a singleton. A factory method can return not only an instance of a class, but also its subtypes. Factory methods can have meaningful names. Etc. etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question