toString in Object

You can look at this piece of code

public class Demo1 {
    static int i=1;

    public static void main(String[] args) {
        System.out.println("love"+new Demo1());
        Demo1 a=new Demo1();
        a.i++;
        System.out.println("me"+a.i);
    }
    public String toString(){
        System.out.print("I ");
        return "java";
    }
}

Output result After
insert image description here
reading, will you have a question why the output is I love java
. First of all, let's take a look at a new Demo1 after love in System.out.println. Here I want to tell you that in System.out A new object in .println will first execute the toString method in this object. If this method is overridden, the overridden method will be executed, but it will not be rushed and the return parameter will be executed after the previous print. return. So first execute the method in toString to print out I and then print out love. When love is printed out, return the java in toString to System.out.println and print it out.
Let's call i in a new Demo1. Because i is a static variable, it will be loaded first when it is loaded, and then it will return 2 after self-addition.

Guess you like

Origin blog.csdn.net/MCYZSF/article/details/89877977
Recommended