Object 类
Object 类
一、clone
-
完整形式
protected native Object clone() throws CloneNotSupportedException
-
此方法用来实现对象的复制,如果要调用这个方法,必须实现
Cloneable
接口和覆盖clone()
方法,还需要在使用克隆的时候处理CloneNotSupportedException
,因为此异常是非运行时异常。 -
默认的覆写,只是浅拷贝,也就是只拷贝基本数据类型,而对于对象的引用数据类型,也只是复制一份引用而已。如果想要实现深拷贝,就需要在覆写的时候,将每一个引用数据类型进行克隆,但是这要求这些引用数据类型也都实现了
Clonable
接口。// 浅拷贝的重写 public class User implements Cloneable{ private int id; private String name; private Date bir; @Override public Object clone() { User user = null; try { user = (User)super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return user; } ... }
// 深拷贝的重写 @Override public Object clone() { User user = null; try { user = (User)super.clone(); user.setBir((Date)this.bir.clone()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return user; }
想要实现完全的深拷贝是很难做到的,因为你不能保证每个引用数据类型都重写了
clone()
,在实际应用中,也很少用的到。
二、finalize
-
完整形式
protected void finalize() throws Throwable
-
此方法是用来释放资源,在垃圾回收器回准备释放该对象的资源时,会调用该方法。主要用在释放资源时,执行一些清除操作。
三、getClass
-
完整形式
public final Class<?> getClass()
-
此方法是返回该对象的运行时类对象。因为java是纯面向对象语言,类型、属性和方法都可以看作是一个对象,所以可以通过类对象可以进行反射的操作,也就是通过类型对象来获取类的属性、方法等。
四、hashCode
-
完整形式
public int hashCode()
-
此方法是返回该对象hash码值。不同的对象有不同的哈希码值,所以在进行对象的比较中或相等判断中要重写此方法。以下是 Eclipse 默认重写的方法:
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bir == null) ? 0 : bir.hashCode()); result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; }
五、equals
-
完整形式
public boolean equals(Object obj)
-
此方法是用来判断该对象与传入的对象是否相同。而该对象默认的实现是比较两个对象引用是否相等,那对于一些对象的判断就不适用了,需要重写此方法,以下是使用Eclipse 重写的方法:
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (bir == null) { if (other.bir != null) return false; } else if (!bir.equals(other.bir)) return false; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
六、toString
-
完整形式
public String toString()
-
当该对象被打印时,会调用这个方法。它的默认输出形式是
getClass().getName() + '@' + Integer.toHexString(hashCode())
七、wait
-
完整形式和它的重载方法
public final void wait() throws InterruptedException public final void wait(long timeout) throws InterruptedException public final void wait(long timeout,int nanos)throws InterruptedException
-
此方法是令当前对象进入等待队列,直到被
notifyAll
、notify
唤醒或者被interrupt
中断。而带参数的重载方法是超过指定时间就进入等待状态,其中 timeout 单位是毫秒,nanos 单位是毫微秒。
八、notify/notifyAll
-
完整形式
public final void notify() public final void notifyAll()
-
notify
是唤醒在此对象监视器上等待的某个线程,而notifyAll
是唤醒在此对象监视器上等待的所有线程。