Object类

作为万类之首的Object类,我们有必要详细全面的了解一下。Object类定义在Object.java文件,属于包java.lang。

       Object类有一个私有方法private static native void registerNatives().

       native是java语言的一个关键字.使用native关键字说明这个方法是原生函数,也就是这个方法是用C/C++语言实现的,并且被编译成了DLL,由java去调用.JDK的源代码中并不包含这些函数的实现体,你应该是看不到的。对于不同的平台它们也是不同的。这也是java的底层机制,实际上java就是在不同的平台上调用不同的native方法实现对操作系统的访问的.

public class Object {

    private static native void registerNatives();

    static {

        registerNatives();

    }

 

    //Java编写的任何类都有一个对应的class对象。比如如果我们编写一个MyString类,那么编译器就会创建一个MyString.class文件,该文件保存了对应于MyString类的Class对象。由于MyString类继承自Object,因此也就继承了下面的这个方法。可以通过调用这个方法获得对应的Class对象。Class对象里面保存了MyString类的信息。后面会仔细总结Class对象的作用。

    public final native Class<?> getClass();//也是native方法,?是通配符,代表Class对象对应的类,比如MyString类。

 

 

       该方法返回hashcode,用于支持哈希容器。

    public native int hashCode();//这里很奇怪是native方法,因为派生类总是提供自己的方法

public int hashCode(),不知道算不算该写了Object类的这个方法,还是提供了自己的同名方法。

 

       该方法用来判断两个对象是否相等,注意这里默认是判断是否为同一个对象。派生类可以改写该方法,转而判断两个不同的对象值是否相等。

    public boolean equals(Object obj) {

       return (this == obj);

    }

 

 

       为了防止意外的使用了clone方法,所以Object.clone方法权限为protected.如果派生类的设计者决定要支持该方法,就会将该方法的访问权限变为public。具体参见后面关于clone的章节。

   protected native Object clone() throws CloneNotSupportedException;

       该方法将会被自动用在和字符串相加的场合,由于这种默认格式不一定是派生类想要的,所以一些派生类可以改写这个方法。

    public String toString() {

       return getClass().getName() + “@” + Integer.toHexString(hashCode());

    }

 

    /**

     * Wakes up a single thread that is waiting on this object’s

     * monitor. If any threads are waiting on this object, one of them

     * is chosen to be awakened. The choice is arbitrary and occurs at

     * the discretion of the implementation. A thread waits on an object’s

     * monitor by calling one of the <code>wait</code> methods.

     * <p>

     * The awakened thread will not be able to proceed until the current

     * thread relinquishes the lock on this object. The awakened thread will

     * compete in the usual manner with any other threads that might be

     * actively competing to synchronize on this object; for example, the

     * awakened thread enjoys no reliable privilege or disadvantage in being

     * the next thread to lock this object.

     * <p>

     * This method should only be called by a thread that is the owner

     * of this object’s monitor. A thread becomes the owner of the

     * object’s monitor in one of three ways:

     * <ul>

     * <li>By executing a synchronized instance method of that object.

     * <li>By executing the body of a <code>synchronized</code> statement

     *     that synchronizes on the object.

     * <li>For objects of type <code>Class,</code> by executing a

    *     synchronized static method of that class.

     * </ul>

     * <p>

     * Only one thread at a time can own an object’s monitor.

     *

     * @exception IllegalMonitorStateException if the current thread is not

     *               the owner of this object’s monitor.

     * @see        java.lang.Object#notifyAll()

     * @see        java.lang.Object#wait()

     */

    public final native void notify();

 

    /**

     * Wakes up all threads that are waiting on this object’s monitor. A

     * thread waits on an object’s monitor by calling one of the

     * <code>wait</code> methods.

     * <p>

     * The awakened threads will not be able to proceed until the current

     * thread relinquishes the lock on this object. The awakened threads

     * will compete in the usual manner with any other threads that might

     * be actively competing to synchronize on this object; for example,

     * the awakened threads enjoy no reliable privilege or disadvantage in

     * being the next thread to lock this object.

     * <p>

     * This method should only be called by a thread that is the owner

     * of this object’s monitor. See the <code>notify</code> method for a

     * description of the ways in which a thread can become the owner of

     * a monitor.

     *

     * @exception IllegalMonitorStateException if the current thread is not

     *               the owner of this object’s monitor.

     * @see        java.lang.Object#notify()

     * @see        java.lang.Object#wait()

     */

    public final native void notifyAll();

 

    /**

     * Causes the current thread to wait until either another thread invokes the

     * {@link java.lang.Object#notify()} method or the

     * {@link java.lang.Object#notifyAll()} method for this object, or a

     * specified amount of time has elapsed.

     * <p>

     * The current thread must own this object’s monitor.

     * <p>

     * This method causes the current thread (call it <var>T</var>) to

     * place itself in the wait set for this object and then to relinquish

     * any and all synchronization claims on this object. Thread <var>T</var>

     * becomes disabled for thread scheduling purposes and lies dormant

     * until one of four things happens:

     * <ul>

     * <li>Some other thread invokes the <tt>notify</tt> method for this

     * object and thread <var>T</var> happens to be arbitrarily chosen as

     * the thread to be awakened.

     * <li>Some other thread invokes the <tt>notifyAll</tt> method for this

     * object.

     * <li>Some other thread {@linkplain Thread#interrupt() interrupts}

     * thread <var>T</var>.

     * <li>The specified amount of real time has elapsed, more or less. If

     * <tt>timeout</tt> is zero, however, then real time is not taken into

     * consideration and the thread simply waits until notified.

     * </ul>

     * The thread <var>T</var> is then removed from the wait set for this

     * object and re-enabled for thread scheduling. It then competes in the

     * usual manner with other threads for the right to synchronize on the

     * object; once it has gained control of the object, all its

     * synchronization claims on the object are restored to the status quo

     * ante – that is, to the situation as of the time that the <tt>wait</tt>

     * method was invoked. Thread <var>T</var> then returns from the

     * invocation of the <tt>wait</tt> method. Thus, on return from the

     * <tt>wait</tt> method, the synchronization state of the object and of

     * thread <tt>T</tt> is exactly as it was when the <tt>wait</tt> method

     * was invoked.

     * <p>

     * A thread can also wake up without being notified, interrupted, or

     * timing out, a so-called <i>spurious wakeup</i>. While this will rarely

     * occur in practice, applications must guard against it by testing for

     * the condition that should have caused the thread to be awakened, and

     * continuing to wait if the condition is not satisfied. In other words,

     * waits should always occur in loops, like this one:

     * <pre>

     *     synchronized (obj) {

     *         while (&lt;condition does not hold&gt;)

     *             obj.wait(timeout);

     *         … // Perform action appropriate to condition

     *     }

     * </pre>

     * (For more information on this topic, see Section 3.2.3 in Doug Lea’s

     * “Concurrent Programming in Java (Second Edition)” (Addison-Wesley,

     * 2000), or Item 50 in Joshua Bloch’s “Effective Java Programming

     * Language Guide” (Addison-Wesley, 2001).

     *

     * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()

     * interrupted} by any thread before or while it is waiting, then an

     * <tt>InterruptedException</tt> is thrown. This exception is not

     * thrown until the lock status of this object has been restored as

     * described above.

     *

     * <p>

     * Note that the <tt>wait</tt> method, as it places the current thread

     * into the wait set for this object, unlocks only this object; any

     * other objects on which the current thread may be synchronized remain

     * locked while the thread waits.

     * <p>

     * This method should only be called by a thread that is the owner

     * of this object’s monitor. See the <code>notify</code> method for a

     * description of the ways in which a thread can become the owner of

     * a monitor.

     *

     * @param      timeout   the maximum time to wait in milliseconds.

     * @exception IllegalArgumentException      if the value of timeout is

     *                 negative.

     * @exception IllegalMonitorStateException if the current thread is not

     *               the owner of the object’s monitor.

     * @exception InterruptedException if any thread interrupted the

     *             current thread before or while the current thread

     *             was waiting for a notification. The <i>interrupted

     *             status</i> of the current thread is cleared when

     *             this exception is thrown.

     * @see        java.lang.Object#notify()

     * @see        java.lang.Object#notifyAll()

     */

    public final native void wait(long timeout) throws InterruptedException;

 

    /**

     * Causes the current thread to wait until another thread invokes the

     * {@link java.lang.Object#notify()} method or the

     * {@link java.lang.Object#notifyAll()} method for this object, or

     * some other thread interrupts the current thread, or a certain

     * amount of real time has elapsed.

     * <p>

     * This method is similar to the <code>wait</code> method of one

     * argument, but it allows finer control over the amount of time to

     * wait for a notification before giving up. The amount of real time,

     * measured in nanoseconds, is given by:

     * <blockquote>

     * <pre>

     * 1000000*timeout+nanos</pre></blockquote>

     * <p>

     * In all other respects, this method does the same thing as the

     * method {@link #wait(long)} of one argument. In particular,

     * <tt>wait(0, 0)</tt> means the same thing as <tt>wait(0)</tt>.

     * <p>

     * The current thread must own this object’s monitor. The thread

     * releases ownership of this monitor and waits until either of the

     * following two conditions has occurred:

     * <ul>

     * <li>Another thread notifies threads waiting on this object’s monitor

     *     to wake up either through a call to the <code>notify</code> method

     *     or the <code>notifyAll</code> method.

     * <li>The timeout period, specified by <code>timeout</code>

     *     milliseconds plus <code>nanos</code> nanoseconds arguments, has

     *     elapsed.

     * </ul>

     * <p>

     * The thread then waits until it can re-obtain ownership of the

     * monitor and resumes execution.

     * <p>

     * As in the one argument version, interrupts and spurious wakeups are

     * possible, and this method should always be used in a loop:

     * <pre>

     *     synchronized (obj) {

     *         while (&lt;condition does not hold&gt;)

     *             obj.wait(timeout, nanos);

     *         … // Perform action appropriate to condition

     *     }

     * </pre>

     * This method should only be called by a thread that is the owner

     * of this object’s monitor. See the <code>notify</code> method for a

     * description of the ways in which a thread can become the owner of

     * a monitor.

     *

     * @param      timeout   the maximum time to wait in milliseconds.

     * @param      nanos      additional time, in nanoseconds range

     *                       0-999999.

     * @exception IllegalArgumentException      if the value of timeout is

     *                       negative or the value of nanos is

     *                       not in the range 0-999999.

     * @exception IllegalMonitorStateException if the current thread is not

     *               the owner of this object’s monitor.

     * @exception InterruptedException if any thread interrupted the

     *             current thread before or while the current thread

     *             was waiting for a notification. The <i>interrupted

     *             status</i> of the current thread is cleared when

     *             this exception is thrown.

     */

   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);

    }

 

    /**

     * Causes the current thread to wait until another thread invokes the

     * {@link java.lang.Object#notify()} method or the

     * {@link java.lang.Object#notifyAll()} method for this object.

     * In other words, this method behaves exactly as if it simply

     * performs the call <tt>wait(0)</tt>.

     * <p>

     * The current thread must own this object’s monitor. The thread

     * releases ownership of this monitor and waits until another thread

     * notifies threads waiting on this object’s monitor to wake up

     * either through a call to the <code>notify</code> method or the

     * <code>notifyAll</code> method. The thread then waits until it can

     * re-obtain ownership of the monitor and resumes execution.

     * <p>

     * As in the one argument version, interrupts and spurious wakeups are

     * possible, and this method should always be used in a loop:

     * <pre>

     *     synchronized (obj) {

     *         while (&lt;condition does not hold&gt;)

     *             obj.wait();

     *         … // Perform action appropriate to condition

     *     }

     * </pre>

     * This method should only be called by a thread that is the owner

     * of this object’s monitor. See the <code>notify</code> method for a

     * description of the ways in which a thread can become the owner of

     * a monitor.

     *

     * @exception IllegalMonitorStateException if the current thread is not

     *               the owner of the object’s monitor.

     * @exception InterruptedException if any thread interrupted the

     *             current thread before or while the current thread

     *             was waiting for a notification. The <i>interrupted

     *             status</i> of the current thread is cleared when

     *             this exception is thrown.

     * @see        java.lang.Object#notify()

     * @see        java.lang.Object#notifyAll()

     */

    public final void wait() throws InterruptedException {

       wait(0);

    }

 

       改写这个方法,派生类可以将一些非托管资源在此处销毁。该方法将在垃圾回收器工作的时候被调用(不能保证一定会被调用)。通常不建议使用该方法,参见后面的章节。

    protected void finalize() throws Throwable { }

}

public class Object

Object 是类层次结构的根类。每个类都使用 Object 作为超类。所有对象(包括数组)都实现这个类的方法

java.lang
接口 Cloneable

public interface Cloneable

此类实现了 Cloneable 接口,以指示 Object.clone()方法可以合法地对该类实例进行按字段复制。

如果在没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法,则会导致抛出 CloneNotSupportedException 异常。

按照惯例,实现此接口的类应该使用公共方法重写Object.clone(它是受保护的)。

注意,此接口包含clone方法。因此,因为某个对象实现了此接口就克隆它是不可能的。即使 clone
方法是反射性调用的,也无法保证它将获得成功

clone

protected native  Object clone()
                throws CloneNotSupportedException
native表示这个方法不是用java编写的,而是在java虚拟机中为本地平台实现的。关键字protected表明这个方法不能被其他包中的类的对象直接调用,因此,可复制的类必须覆盖这个方法,并将可视修饰符改为public,以便在任何包中都可以使用这个方法。因为Object类中为本地平台实现的clone方法支行复制对象的任务,所以,可复制类中的clone方法只需简单的调用super.clone()。定义在Object中的clone方法可能抛出CloneNotSupportedException一场,这样super.clone必须放在try/catch块中。这种情况下,对于可复制类内部的其他类的对象执行的是浅复制,即:如果域是一个对象,复制的是域的引用而不是域的内容。如果进行深复制,需要使用自定义的复制操作覆盖clone方法,而不是简单的调用super.clone()。

创建并返回此对象的一个副本。“副本”的准确含义可能依赖于对象的类。一般来说,对于任何对象 x,如果表达式:

x.clone() != x

是正确的,则表达式:

x.clone().getClass() == x.getClass()

将为true,但这些不是绝对条件。一般情况下是:

x.clone().equals(x)

将为true,但这不是绝对条件。

按照惯例,返回的对象应该通过调用 super.clone 获得。如果一个类及其所有的超类(Object 除外)都遵守此约定,则
x.clone().getClass() ==x.getClass()

按照惯例,此方法返回的对象应该独立于该对象(正被克隆的对象)。要获得此独立性,在 super.clone 返回对象之前,有必要对该对象的一个或多个字段进行修改。这通常意味着要复制包含正在被克隆对象的内部“深层结构”的所有可变对象,并使用对副本的引用替换对这些对象的引用。如果一个类只包含基本字段或对不变对象的引用,那么通常不需要修改
super.clone 返回的对象中的字段。

Object 类的 clone 方法执行特定的克隆操作。首先,如果此对象的类不能实现接口Cloneable,则会抛出
CloneNotSupportedException。注意:所有的数组都被视为实现接口Cloneable。否则,此方法会创建此对象的类的一个新实例,并像通过分配那样,严格使用此对象相应字段的内容初始化该对象的所有字段;这些字段的内容没有被自我克隆。所以,此方法执行的是该对象的“浅表复制”,而不“深层复制”操作。

Object 类本身不实现接口 Cloneable,所以在类为 Object 的对象上调用 clone 方法将会导致在运行时抛出异常。

equals

public boolean equals(Object obj)

指示某个其他对象是否与此对象“相等”。

equals 方法在非空对象引用上实现相等关系:

·        自反性:对于任何非空引用值 xx.equals(x) 都应返回
true

·        对称性:对于任何非空引用值 xy,当且仅当
y.equals(x) 返回 true 时,x.equals(y) 才应返回
true

·        传递性:对于任何非空引用值 xy
z
,如果 x.equals(y) 返回 true,并且y.equals(z) 返回
true,那么x.equals(z) 应返回 true

·        一致性:对于任何非空引用值 xy,多次调用
x.equals(y) 始终返回 true 或始终返回 false,前提是对象上
equals
比较中所用的信息没有被修改。

·        对于任何非空引用值 xx.equals(null) 都应返回
false

Object 类的 equals 方法实现对象上差别可能性最大的相等关系;即,对于任何非空引用值x
y,当且仅当 xy 引用同一个对象时,此方法才返回truex == y 具有值
true)。

注意:当此方法被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相等对象必须具有相等的哈希代码。

注意:我们在继承Objext类的equals()方法时一般都要对这个方法进行重写,因为Object类的equals()方法的实现只是简单的检查两个引用值是否指向同一个对象,而正常情况下我们需要解决的问题是连个对象引用的值是否相等,而不是两个引用是否指向同一个对象。

hashCode

public int hashCode()

返回该对象的哈希代码值。支持该方法是为哈希表提供一些优点,例如,java.util.Hashtable 提供的哈希表。

hashCode 的常规协定是:

·        在 Java 应用程序执行期间,在同一对象上多次调用 hashCode 方法时,必须一致地返回相同的整数,前提是对象上
equals 比较中所用的信息没有被修改。从某一应用程序的一次执行到同一应用程序的另一次执行,该整数无需保持一致。

·        如果根据 equals(Object)方法,两个对象是相等的,那么在两个对象中的每个对象上调用
hashCode 方法都必须生成相同的整数结果。

·        以下情况 是必需的:如果根据 equals(java.lang.Object) 方法,两个对象不相等,那么在两个对象中的任一对象上调用
hashCode 方法必定会生成不同的整数结果。但是,程序员应该知道,为不相等的对象生成不同整数结果可以提高哈希表的性能。

实际上,由 Object 类定义的hashCode 方法确实会针对不同的对象返回不同的整数。(这一般是通过将该对象的内部地址转换成一个整数来实现的,但是 JavaTM编程语言不需要这种实现技巧。)

toString

public String toString()

返回该对象的字符串表示。通常,toString 方法会返回一个“以文本方式表示”此对象的字符串。结果应是一个简明但易于读懂。建议所有子类都重写此方法。

Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例)、at 标记符“@”和此对象哈希代码的无符号十六进制表示组成。换句话说,该方法返回一个字符串,它的值等于:

getClass().getName() + '@' + Integer.toHexString(hashCode())

finalize

protected void finalize()
                 throws Throwable

当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。子类重写finalize 方法,以配置系统资源或执行其他清除。

finalize 的常规协定是:当 JavaTM 虚拟机已确定尚未终止的任何线程无法再通过任何方法访问此对象时,将调用此方法,除非由于准备终止的其他某个对象或类的终结操作执行了某个操作。finalize 方法可以采取任何操作,其中包括再次使此对象对其他线程可用;不过,finalize 的主要目的是在不可撤消地丢弃对象之前执行清除操作。例如,表示输入/输出连接的对象的 finalize 方法可执行显式 I/O 事务,以便在永久丢弃对象之前中断连接。

Object 类的 finalize 方法执行非特殊性操作;它仅执行一些常规返回。Object 的子类可以重写此定义。

Java 编程语言不保证哪个线程将调用某个给定对象的finalize 方法。但可以保证在调用 finalize 时,调用 finalize 的线程将不会持有任何用户可见的同步锁定。如果 finalize 方法抛出未捕获的异常,那么该异常将被忽略,并且该对象的终结操作将终止。

在启用某个对象的 finalize 方法后,将不会执行进一步操作,直到 Java 虚拟机再次确定尚未终止的任何线程无法再通过任何方法访问此对象,其中包括由准备终止的其他对象或类执行的可能操作,在执行该操作时,对象可能被丢弃。

对于任何给定对象,Java 虚拟机最多只调用一次 finalize 方法。

finalize 方法抛出的任何异常都会导致此对象的终结操作停止,但可以通过其他方法忽略它。

getClass

public final Class<? extends Object> getClass()

返回一个对象的运行时类。该Class 对象是由所表示类的 static synchronized 方法锁定的对象。

返回:

表示该对象的运行时类的java.lang.Class 对象。此结果属于类型 Class<? extends X>,其中 X 表示清除表达式中的静态类型,该表达式调用getClass

 

 

 

Keep it simple!

作者:N3verL4nd
出处:http://www.cnblogs.com/lgh1992314/
知识共享,欢迎转载。

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注