我在一些 Java 编程竞赛中找到了一个任务。必须创建仅具有一个参数“文本”和一个构造函数的类 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.
一个构造函数如何提供不同的参数集?是否有类似动态构造函数的东西可以识别发送的值?
最佳答案
利用varargs .
public class Sentence {
public Sentence(Object... text) {
// ...
}
}
自己填写构造函数逻辑。然而,确定所有类型可能会变得有点糟糕。您可以利用 Object#toString()
并让 Sentence
类也实现它。
关于java - 一个构造函数 - 多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2373419/