Java 源代码分析
Object类——一切类的父类
(1)Object类的声明
package ; //
public class Object
(2)hashCode方法
public native int hashCode();
(3)(重要)equals( )方法——比较对象的引用
Object类的equals( )方法比较的是对象的引用而不是内容,这与实际生活的情况不符,实际生活中人们要求比较的是内容,比较引用没有意义,所以其他类继承Object类之后,往往需要重写equals( )方法
public boolean equals(Object obj) {
return (this == obj);
}
(4)(重要)toString( )方法——打印对象的信息
打印一个对象就是调用toString( )方法,该方法打印这个对象的信息,其他类在继承Object类后,一般要重写此方法,设置打印关于对象的信息的操作。
public String toString() {
return getClass().getName()+"@"+(hashCode());
}
(5)线程的等待
public final void wait() throws InterruptedException {
wait(0);
}
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 value out of range");
}
if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
timeout++;
}
wait(timeout);
}
(6)唤醒等待的线程
public final native void notify();
唤醒全部线程,哪个线程的优先级高,他就有可能先执行
public final native void notifyAll();
(7)finalize()方法——对象的回收
当确定一个对象不会被其他方法再使用时,该对象就没有存在的意义了,就只能等待JVM的垃圾回收线程来回收了。垃圾回收是以占用一定内存资源为代价的。();就是启动垃圾回收线程的语句。当用户认为需要回收时,( ).gc( );();来回收内存。(();调用的就是Runtime类的gc( )方法)
当一个对象在回收前想要执行一些操作,就要覆写Object类中的finalize( )方法。
protected void finalize() throws Throwable { }
注意到抛出的是Throwable,说明除了常规的异常Exceprion外,还有可能是JVM错误。说明调用该方法不一定只会在程序中产生异常,还有可能产生JVM错误。
(8)clone( )方法——用于对象克隆
Object类的直接或间接子类通过在重写该方法并直接调用本类的该方法完成对象克隆。
protected native Object clone() throws CloneNotSupportedException;
native关键字表示要调用本机操作系统的函数。
2. String类
(1)String类声明
String类实现了序列化、比较器两个接口,
用final修饰说明该类不能被其他类继承,其他类不能重写该类已有的方法
package ; //
public final class String
implements
java源代码 来自淘豆网m.daumloan.com转载请标明出处.