首页 > 解决方案 > 为什么 Java 中的内置类没有默认构造函数,但在创建该类的对象时需要传递参数?

问题描述

为什么 Java 中的内置类没有默认构造函数,但在创建该类的对象时需要传递参数?

例子:

public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence

public final class Array
extends Object

标签: javaconstructorargumentsdefault-constructor

解决方案


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.


推荐阅读