toString方法的应用
2021-11-03 本文已影响0人
哈迪斯Java
package HspLearningPoly.poly01.Obj;
public class ToString01 {
public static void main(String[] args) {
/*
getClass().getName() 类的全类名(包名+类名)
Integer.toHexString(hashCode())将对象的hashcode值转成16进制
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
*/
Monster monster = new Monster("猴子", "砍柴", 1233.2);
System.out.println(monster.toString()+"monster.hashCode()="+monster.hashCode());
System.out.println("当直接输出一个对象时,toString方法会被默认的调用");
System.out.println(monster);
}
}
class Monster{
private String name;
private String job;
private double salary;
public Monster(String name, String job, double salary) {
this.name = name;
this.job = job;
this.salary = salary;
}
}
输出结果为:
HspLearningPoly.poly01.Obj.Monster@1b6d3586monster.hashCode()=460141958
当直接输出一个对象时,toString方法会被默认的调用
HspLearningPoly.poly01.Obj.Monster@1b6d3586