How to use the toString method in Java?

前端 未结 13 879
说谎
说谎 2020-11-21 06:26

Can anybody explain to me the concept of the toString() method, defined in the Object class? How is it used, and what is its purpose?

13条回答
  •  你的背包
    2020-11-21 06:55

    The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.

    Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:

    public class Contact {
      private String firstName;
      private String lastName;
      public Contact (String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
      }
      public String getFirstName() {return firstName;}
      public String getLastName() {return lastName;}
    
      public String getContact() {
        return firstName + " " + lastName;
      }
    
      @Override
      public String toString() {
        return "["+getContact()+"]";
      }
    }
    

提交回复
热议问题