一个构造函数-多个参数 [英] One constructor - multiple arguments

查看:77
本文介绍了一个构造函数-多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've found a task on some Java programming competition. One must create class Sentence with only one argument 'text' and only one constructor. Here's sample test code :

 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.

一个构造函数如何服务于不同的参数集?是否有诸如动态构造函数之类的东西可以识别发送的值?

How one contructor can serve different sets of arguments ? Is there something like dynamical constructor which recognizes sent values?

推荐答案

使用 varargs

public class Sentence {

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

}

自己填写构造函数逻辑。但是,确定所有类型可能有点麻烦。您可以使用 Object#toString()并让 Sentence 类也实现一个。

Fill in the constructor logic yourself. It may however become a bit awful to determine all the types. You could make use of Object#toString() and let the Sentence class implement one as well.

这篇关于一个构造函数-多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆