Reputation: 3628
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?
Upvotes: 2
Views: 5138
Reputation: 597006
Yes, java 5+ support varargs - you can pass mulitple arguments of the same type, like this:
public Constructor(Object... args){..}
public void methodName(Object... args){..}
Then the arguments are accessible as an array of Object
. But that's not always a good practice. Varargs should be used only for arguments with the same logical type. For example, a list of names. If multiple arguments should be passed I'd suggest to overload constructors.
In this case the arguments are all of the same logical type - "word", so this is a nice way to do it.
Upvotes: 2
Reputation: 27464
If you accept Object... value, then you can convert anything to a string with toString. toString is defined on Object so every Object should support it.
Upvotes: 1
Reputation: 1108537
Make use of varargs.
public class Sentence {
public Sentence(Object... text) {
// ...
}
}
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.
Upvotes: 7