首先来看下面这段代码
package com.test; public class ToStringTest { static int i = 1; public static void main(String[] args) { System.out.println("love "+new ToStringTest()); System.out.println(new ToStringTest()); ToStringTest a = new ToStringTest(); a.i++; System.out.println("me "+a.i); } public String toString(){ System.out.print("I "); return "java"; } }
运行结果为:
代码运行后,先加载静态变量,然后执行main方法。
在main方法中执行第一个语句System.out.println("love "+new ToStringTest() ),语句由内向外执行,先执行new ToStringTest(),当执行此行代码时会先创建了本类的对象,由于此类重写了在Object类里面的toString方法,首先会调用本类里面的toString方法,打印输出 “ I ”,然后返回“java ”,再打印输出Java
在Java中“System.out.println(类对象名);”实际输出的是该对象的toString()方法返回的字符串,new ToStringTest()等价于类匿名对象名.toString(),toString方法的好处是在碰到println方法的时候会被自动调用,不用显式的写出来。