-
toString()
class User {
int id;
public User(int id) {
this.id = id;
}@Override
public String toString() {
return "User{id=" + id + "}";
}
}
public class Test {
public static void main(String[] args) {
System.out.println(new User(1001));
}
}
作用:默认打印对象地址,重写后打印对象属性,方便调试日志。
-
equals()
class User {
int id;
public User(int id) {
this.id = id;
}@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return ((User)o).id == this.id;
}
}
作用:默认比较地址,重写后实现内容比较。
- getClass()
public class Test {
public static void main(String[] args) {
Object obj = new User();
System.out.println(obj.getClass().getName());
}
}
作用:获取对象运行时真实类型,是反射基础。
-
clone()
class User implements Cloneable {
int id;@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
作用:快速拷贝对象(浅拷贝),必须实现 Cloneable 。
总结
- toString:日志打印必备
- equals:实现对象内容判等
- getClass:反射核心
- clone:快速浅拷贝对象
