java - 为什么 Java 中的内置类没有默认构造函数,但在创建该类的对象时需要传递参数?
问题描述
为什么 Java 中的内置类没有默认构造函数,但在创建该类的对象时需要传递参数?
例子:
public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence
public final class Array
extends Object
解决方案
As was mentioned by RealSkeptic, constructors are useful in cases where a usable object can be created without having to pass any arguments to the constructor. It's not all that useful to have an Integer
without a set value, so it requires an int
(or a String
that can be converted to an int
) to be passed to its constructor.
There are some classes in the java library that do have default constructors, but only when they're likely to be helpful.
To go over the examples you mentioned:
String
does have a default constructor to create an empty string. It's not really useful due to the immutability of strings, but it can still be used when necessary.
Array
contains only static methods and shouldn't be instantiated for any reason.
推荐阅读
- r - 使用 dateInput 作为要从中抓取的 url 的日期组件
- javascript - 如何在javascript中正确添加天数
- google-calendar-api - Google Calendar Api(事件:观看)不适用于其他 CalendarIds
- javascript - 如何在传单中的标记下方添加文本?
- window - 当某些键到达太慢时,Flink eventTime 键控窗口不会触发
- c# - UWP:如何设置 RichTextBlock 的默认选项卡大小?
- c++ - 从同一个文件读取和写入?
- json - 无法通过 python3 从 AWS Secrets Manager 正确访问 GPG 公钥/私钥
- javascript - [vue]:如何在 Vue 中的同一元素上使用 css 模块和普通类 css 添加动态类?
- ldap - LDAP 查询,两组,一组包含用户,另一组包含用户组