Object类是所有类、数组的父类。
任何Java的普通类都是Object的子类,都可以调用Object类的方法:
boolean equals(Object obj) 判断指定对象与该对象的地址是否相等
protected void finalize() 当系统变量没有引用到该对象时,垃圾回收器调用此方法来清理该对象的资源
Class<> getClass() 返回该对象的运行时类
int hashCode() 返回该对象的hashCode值,默认情况下和System类的identityHashCode(Object x)方法计算出的结果相同。
String toString() 返回该对象的字符串表示,当对象在被System.out.println()输出,或者把对象和某个字符串拼接时,系统会自动调用该方法。该方法默认返回“运行时类名@十六进制的hashCode值”格式的字符串
wait()
notify()
notifyAll()
protected Object clone() “自我克隆”得到一个当前对象的副本,并把二者完全隔离。
“克隆”的步骤:
实现Cloneable接口。(这是一个标志性的接口,实现该接口的对象可以实现“自我克隆”,接口里没有定义任何方法)
实现自己的clone()方法。(实现clone()方法时通过super.clone())
class Address{ String detail; public Address(String detail){ this.detail = detail; } } //实现Cloneable接口 class User implements Cloneable{ int age; Address address; public User(int age){ this.age = age; address = new Address("中国"); } //通过调用super.clone()来实现clone()方法 public User clone() throws CloneNotSupportedException { return (User)super.clone(); } } public class CloneTest { public static void main(String[] args) throws CloneNotSupportedException { User u1 = new User(18); User u2 = u1.clone(); System.out.println(u1==u2); //false System.out.println(u1.age == u2.age); //true } }
Object类提供的clone机制十分高效,比如clone一个包含100个元素的int[]数组,用clone方法比静态copy方法快近2倍。
Object类的clone机制只对对象里的各实例变量进行“简单复制”,如果实例变量的类型是引用类型,Object的clone机制也只是简单的复制这个引用变量(地址)。所以,这是一种浅克隆,不会对成员变量所引用的对象进行clone。如果需要“深度克隆”,则需要开发者自己进行“递归”克隆。
原文:https://www.cnblogs.com/woshi123/p/12484231.html