toString介绍
Object 类是所有对象的父类。
而Object类中含有toSting()方法,因此所有的对象都包含有一个toString()方法。
toString方法主要的作用:
toString是对类与对象的信息进行描述。
当对对象进行打印输出的时候,可以发现,直接输出对象与调用对象的toString()方法产生的效果是一致的。
因为当去输出对象的时候,调用的也是对象的toString()方法,只不过不可见。
public class Demo {
public static void main(String[] args) {
Student stu = new Student("sky","男");
System.out.println(stu); //com.sky2101.Student@3f3afe78
System.out.println(stu.toString());//com.sky2101.Student@3f3afe78
}
}
class Student {
String name;
String sex;
// int age;
//定义一个有参构造方法
public Student(String name, String sex) {
this.name = name;
this.sex = sex;
// this.age = age;
}
}
当使用toString()方法对对象进行描述的时候,他输出的格式是:类名+@+hashCode(哈希值)。
hashCode是通过将对象的地址转换成一个整数来实现的。
hashCode():返回的是一个十进制的整数,而toString()方法当中打印输出的是一个十六进制的值,他们相同。
public class Demo {
public static void main(String[] args) {
Student stu = new Student("sky","男");
System.out.println(stu); //com.sky2101.Student@3f3afe78
System.out.println(stu.toString());//com.sky2101.Student@3f3afe78
//打印哈希值,默认十进制
System.out.println(stu.hashCode());//1060830840
//十进制转十六进制
System.out.println(Integer.toHexString(stu.hashCode()));//3f3afe78
}
}
class Student {
String name;
String sex;
// int age;
//定义一个有参构造方法
public Student(String name, String sex) {
this.name = name;
this.sex = sex;
// this.age = age;
}
}