Detailed explanation of toString method



/* The purpose of sun designing the toString method in the object class is to return the string representation of the java object. If the object is represented
by a string on the console, if the string is displayed, use the toString method

In the actual development process, the toString method in Object is not enough
because the result of the toString method in Object is not satisfactory

The toString method in Object is to be rewritten, and many other methods are also to be rewritten

The public String that implements the toString method in sun
  toString(){
   return getClass().getName+"@"+Integer.toHexString(hashcode());
  }
  
  The toString method in Object returns: the memory address of the class name @java object passes through The int type value obtained by the hash algorithm is converted into hexadecimal
  . The output result can be regarded as the memory address of the java object in the heap
*/
public class fuck1{
  public static void main(String[] args){
    Object o1 =new Object();
   
    String ostr=o1.toString();
    System.out.println(ostr);  //java.lang.Object@15db9742
   
    person p1=new person("hah",15);
    String pstr=p1 .toString();
    System.out.println(pstr);//person@6d06d69c
   
    person p2=new person("newb",11);
    System.out.println(p2);
   
    //If the parentheses after the print method are one For reference types, the toString method of the reference type will be called by default.
    System.out.println(p2.toString());
  }
}

class person{
 String name;
 int age;
 
 person(String name,int age){
  this.name=name;
  this.age=age;
 }
 //改写toString方法
 public String toString(){
  return "person:"+this.name+",age"+age;
 }
 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325891309&siteId=291194637