标签:load sys 结果 sync 对象 rgs equals print class
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}
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();
}
JAVA基础复习一 Object类的toString()方法剖析
标签:load sys 结果 sync 对象 rgs equals print class
原文地址:https://www.cnblogs.com/elnimo/p/13234504.html