What is the function of the toString() method?

Asked

Viewed 2,048 times

15

What is the function of toString() in Java? Why do we do System.out.println(compObjeto) and in the main() (assuming there is an object for the class comp called compObjeto), he does print of toString()?

public class comp {

    private String nome;
    private Data aniversario;

    public comp (String n, Data a){
        nome=n;
        aniversario=a;

    }

    public String toString(){

        return String.format("O teu nome é %s , e a fazes anos no dia %s", nome, aniversario);
    }

}

3 answers

17


As the name says, what it does is it results in a text that expresses what that object is, so every object has this method.

There is some controversy about the right conceptual use.

My understanding, and many much more experienced people and with training (in the broad sense, not from certified study only) much better than I, understand that this is a debugging function or at most for converting data to serialization or some very specific activity that has more to do with the mechanism than with the business rule.

There are those who disagree with that, and in Java there seems to be a culture of being more than that, which shows a strange culture because it’s a language that tries to do the right thing, even if it’s not always practical, and this along with exceptions and other things in language, seek the most practical even if conceptually wrong.

There are still those who think they can do anything on it, can even write on the console or on a GUI screen. This I think that everyone who understands something about software development agrees that it is abuse, at least conceptually. And everything that is conceptually wrong in real, complex code one day explodes in your face. AP code is right at this point.

But from the previous concept he’s wrong because he’s defining business rule, it’s resulting in something to be used in the application, probably with user interaction, which is not the goal of toString().

This method should only return the simple identity of the object. Anything that indicates what this object is, what its important content is as basic as possible.

If you want a formatted message, create a method to return it. If you want to use something standardized, you can even use a toString(alguma coisa) (so with a different signature of what is in every object) which is already something that is not used to meet the needs of the mechanism. But it can be another method as well. Java does not have a standardization for this. Java was created at a time when much was not yet perceived as wrong.

Of course in the example used is not something so critical because it does a little what it needs, but it has a lot of penduricalho.

Let’s get the documentation provided by Math in his reply in another question:

Returns a string representation of the Object. In general, the toString method Returns a string that "textually represents" this Object. The result should be a Concise but informative representation that is easy for a person to read. It is Recommended that all subclasses override this method.

Is this form representative of the object? Is it concise? I don’t think so, until I answered there. Java actually encourages right, but many people don’t interpret it that way in the documentation. So I strongly disagree with Math’s response there.

Has more:

The toString method for class Object Returns a string consisting of the name of the class of which the Object is an instance, the at-Sign Character `@', and the unsigned hexadecimal representation of the hash code of the Object. In other words, this method Returns a string Equal to the value of:

It says you should use the class name. Of course giving some identity value is more useful than just the name, it will have advantages. The default implementation of this method in most classes is like this, returns the class name and not the object identity (understand the difference). It is for purification purposes. Even a reflection (good) of poor.

Think, if one day you need to return a different text, what will you do? Change this text? What if the application depends on that specific text to do something? After all the method is mechanism, it can be used for anything involving representation and it should be stable, the result is part of the contract of API. And if you really need to change, you have to create another method, it would become a mess because it’s mixing functions.

Adorn the text of toString() was the right Integer it should be like this:

public String toString() {
     return String.format("O valor do objeto é %s", String.valueOf(value);
 }

That’s what you’re doing in the question class. That’s very wrong.

I prefer it this way:

public class comp {
    private String nome;
    private Data aniversario;
    public comp (String n, Data a) {
        nome = n;
        aniversario = a;
    }
    public String toString() {
        return String.format("%s - %s", nome, aniversario);
    }
    public String getTextual() {
        return String.format("O teu nome é %s , e a fazes anos no dia %s", nome, aniversario);
    }
}

I put in the Github for future reference.

Maybe it could even be: String.format(nome);, I don’t think too much birthday is part of the identity. The secondary method was just a simple example, in real application I don’t even know if I would do it, I don’t even know if there would be something like that in the object, I think it can be a business rule pluggable, but that’s another matter.

  • What is the object in my example ? is the constructor ?

  • @Pedrogouveia no, in this code there is no object yet, there is only the class. https://answall.com/q/100812/101. Constructor is another thing https://answall.com/q/73530/101. In this class you only have one constructor and the toString() defined. Hence the question in System.out.println(compObjeto), the variable compObjeto stores the object that will only exist at execution time.

  • thank you so much for all the work! What is the advantage of being Return String.format ("%s - %s", name, birthday); and not being Return String.format ("Your name is %s, and you birthday it %s", name, birthday);?

  • toString is only a standard if there are any problems or so ?

  • @Pedrogouveia improved the answer, it is a matter of concept and proper use of the mechanism. It was not meant to pass messages to the user, which uses the wrong concept may even work, but one day pays a price for it. This method is standard for internal use of the application. It is to take information without wrinkles, to treat brutally. There are people who think that should not be part of the hierarchy of types and be a detail of implementation, more a call convention. But then the subject goes deeper than your question speaks.

  • thank you very much I understand!

  • Okay I didn’t want to be too boring but just to be sure ,basically toString "defines" a String for a class ?

  • @Pedrogouveia I prefer the more formal definition, it defines a text that represents the object (and not the class). A described text is not the same as representative. What you used is descriptive. Note that some people think this is right, but I’ve never seen a good argument that says why it’s right.

Show 3 more comments

9

toString

public String toString()

Returns a textual representation of the Object. The result must be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses replace this method. The method toString for the class Object returns a string of characters consisting of the class name of which the object is an instance @, and the unsigned hexadecimal representation of code hash of the object(Example). In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

In this reply from SO-EN, there are a number of examples that can better clarify your doubts.

  • What is the object in my example ? is the constructor ?

  • @Pedrogouveia edited the question with a question from SO-EN. There is a series of answers that can help to better understand how the ToString

9

The method toString() serves to generate a textual identity that matches the target object.

Every time the target object needs to be converted to a String, usually in order to print it on the console or in a log file, the method toString() is called.

Every Java object already has a default implementation of toString(). Who is responsible for this implementation is the class Object, which all classes extend by default. In the default implementation, when a print of the object is printed the Fullname of the class following by "@" + the memory address of the object.

Therefore, it is sometimes necessary to overwrite the method toString(), since printing the default implementation is not very user friendly.

  • The constructor in the example I gave in this case is the object ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.