Question

I have a varargs constructor like this :

public class Sentence {

   public String[] str;

      public Sentence(Object... text){

        StringBuilder sb = new StringBuilder();
        for (Object o : text) {
          sb.append(o.toString())
          .append(" ");
        }
        System.out.println(sb.toString());

     }

 }

The class can can accept various types of data via this constructor (ints, strings, and Sentence objects as well). How do I create a proper toString method for such a class?

Was it helpful?

Solution

Not sure exactly what you're trying to achieve, but as the toString() method...

Returns a string representation of the object

...I guess I would store the result of your sb.toString() call as a member String variable (say private String asString), and return that in a toString() method overriding the method in Object:

public String toString() {
  return this.asString;
}

OTHER TIPS

You can't print Sentence in toString because you can get infinite loop if you initialize 2 Senence objects by each other.

So, print all strings and objects and if it's possible some data from Sentence object, or only "1 sentence object" to point that it's also passed as an init param.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top