toString()的重载

一般用System.out.println();时,括号里面都默认调用toString()方法。

例如:h = 20;

   System.out.println(h.toString()); 与 System.out.println(h);相同


Hello类中:

public Hello(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

在Test类use()方法中调用Hello类,并输出

public void use() {

		Hello h = new Hello(6, "静静", 20);
		System.out.println(h); // 默认为h.toString()
	}

直接输出时,结果如下:

edu.u.Hello@5b37e0d2

但是在Hello类中重载一下toString()方法,就会输出你想要的结果(注意:是在Hello类中重载哦)

public String toString() {
        return "ID = "+ id +" name = "+ name +" age = "+age;
    }
	

ruturn出你想输出的形式

则再运行时如下

ID = 6 name = 静静 age = 20
这样就完成了!


猜你喜欢

转载自blog.csdn.net/zxl1148377834/article/details/80301667