java Object toString method

1. The toString method of Object :

1. public String toString() returns the address information of the current object in the heap memory by default : the full name of the class@memory address

2. When directly outputting objects during development, the address of the default output object is actually meaningless. Therefore, this method should be rewritten by subclasses to return the content information of the object instead of the address information.

public class ToString {
    public static void main(String[] args) {
      MethodObject1.student s1=new student(1111,"小明");
        System.out.println(s1.toString());//默认可以省略tostring
    }
}
class student{
    private int Sno;
    private String name;

    public student(int sno, String name) {
        Sno = sno;
        this.name = name;
    }

    public int getSno() {
        return Sno;
    }

    public void setSno(int sno) {

        Sno = sno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

  @Override
    public String toString() {
        return "student{" +
                "Sno=" + Sno +
                ", name='" + name + '\'' +
                '}';
    
}

 After commenting out the overriding method, the following address is output:

After uncommenting:

 

Guess you like

Origin blog.csdn.net/weixin_51757999/article/details/125768365
Recommended