Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One constructor - multiple arguments

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?

like image 889
sasklacz Avatar asked Sep 05 '26 11:09

sasklacz


2 Answers

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.

like image 115
BalusC Avatar answered Sep 07 '26 01:09

BalusC


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.

like image 40
Bozho Avatar answered Sep 07 '26 00:09

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!