JAVA基础复习一 Object类的toString()方法剖析
Object在java中是所有类的父类,默认所有类都继承了Object类。
Object类的结构,可以发现其最常见的toString()与equals()方法,还有getClass()方法。
Object类的toString()方法源码:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
示例:
package com.winson.ObjectClass;
/**
* @description:Object类中的toString()方法剖析
* @date: 2020/7/4 11:35
* @author: winson
*/
public class ObjectTest {
public static void main(String[] args) {
Person person = new Person("小明", 20);
System.out.println(person);
System.out.println(person.toString());
}
}
class Person{
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
如上:自定义的Person类并未将父类Object中的toString()方法进行重写,测试结果:
com.winson.ObjectClass.Person@45ee12a7
com.winson.ObjectClass.Person@45ee12a7
如果我们想要获取自定义类的值,必须重写toString()方法:
class Person{
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
重写toString()方法后的结果,当然,我们也可以自定义其格式。
Person{name='小明', age=20}
Person{name='小明', age=20}
注:当我们输出一个对象的引用时,实际上就是调用当前对象的toString()方法
System.out.println(person);
//println()方法的源码:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
//String的valueOf()方法的源码
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}