一.什么是Object类?
Object类是所有Java类的父类,包括我们自己所写的类和数组。然而接口是不继承Object类的。Object类属于java.lang包,此包下的所有类在使用时无需手动导入,系统会在程序编译期间自动导入。在实际使用的时候,所有类默认继承Object类,可以不必写extends Object关键字,写了也不会报错。也就是说,下面两种类的定义效果都是一样的:
class student {}
class student extends Object{}
使用Object类可以接收所有类的对象,如下:
Object student = new Student();
二.Object类提供了11个方法
public final native Class<?> getClass();
public native int hashCode();
public boolean equals(Object obj){
return (this == obj);
}
protected native Object clone() throws CloneNotSupportedException;
public String toString(){
return getClass.getName() + "@" + Integer.toHexString(hashCode());
}
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout,int nanos)throws InterruptedException{
if(timeout<0){
throw new IllegalArgumentException("timeout value is negative");
}
if(nanos<0 || nanos>999999){
throw new IllegalArgumentException("nanosecond timeout out of range!");
}
if(nanos>500000 || (nanos!=0 && timeout == 0)){
throw new IllegalArgumentException("nanosecond timeout out of range!");
}
wait(timeout);
}
public final void wait() throws InterruptedException{
wait(0);
}
protected void finalize() throws Throwable{}
下面会详细的分析每一个方法。
三.protected native Object clone() throws CloneNotSupportException
修饰词解析:
- native修饰的方法调用了非Java代码的接口,执行效率比非native修饰的方法效率高
- protected一个类在覆盖clone方法的时候,需要修改成public修饰符,这样才能保证可以访问该方法,否则不能调用,以下代码无效:
Object obj = new Object();
Object clone = obj.clone();
返回值:
返回一个Object对象,所以必须要进行强制类型转换才能得到我们需要的类型,假设MyClass是可克隆的,克隆代码如下:
MyClass mc = new MyClass();
MyClass clone = (MyClass)mc.clone();
解析得知:
- 创建并返回此对象的副本
- 被克隆的对象需要implements cloneable对象,否则会抛出CloneNotSupportException异常
- Object类本身并不实现接口Cloneable,因此在为类别为Object的对象上调用clone方法将导致运行出错
- 要调用clone方法,需要将调用放在try-catch块中,或者重新抛出异常
- x.clone() != x,克隆出来的对象和原来的对象不是同一个,指向不同的内存地址
- x.clone().getClass() == x.getClass(),是同一类型的对象
- x.clone().equals(x),对于原生类型是复制一个,而对于包