一个构造函数 - 多个参数

owc*_*wca 2 java constructor dynamic

我在一些Java编程竞赛中找到了一个任务.必须创建只有一个参数'text'且只有一个构造函数的类Sentence.这是测试代码示例:

 Sentence s1=new Sentence("only","CAT"),
      s2=new Sentence("and", 2, "mice"),
      s3=new Sentence(s1,s2,"completely","alone"),
      s4=new Sentence(s3, "on the ", new Integer(32), "th street");

 System.out.println(s1); Only cat.
 System.out.println(s2); Only cat and 2 mice.
 System.out.println(s3); Only cat and 2 mice completely alone.
 System.out.println(s4); Only cat and 2 mice completely alone on the 32th street.
Run Code Online (Sandbox Code Playgroud)

一个构造函数如何提供不同的参数集?有没有像动态构造函数那样识别发送值的东西?

Bal*_*usC 7

利用varargs.

public class Sentence {

    public Sentence(Object... text) {
        // ...
    }

}
Run Code Online (Sandbox Code Playgroud)

自己填写构造函数逻辑.然而,确定所有类型可能会有点糟糕.您可以使用Object#toString()并让Sentence类实现一个.