1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17/*
18 * Copyright (C) 2008 The Android Open Source Project
19 *
20 * Licensed under the Apache License, Version 2.0 (the "License");
21 * you may not use this file except in compliance with the License.
22 * You may obtain a copy of the License at
23 *
24 *      http://www.apache.org/licenses/LICENSE-2.0
25 *
26 * Unless required by applicable law or agreed to in writing, software
27 * distributed under the License is distributed on an "AS IS" BASIS,
28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 * See the License for the specific language governing permissions and
30 * limitations under the License.
31 */
32
33package java.lang;
34
35/**
36 * The root class of the Java class hierarchy. All non-primitive types
37 * (including arrays) inherit either directly or indirectly from this class.
38 *
39 * <a name="writing_equals"><h4>Writing a correct {@code equals} method</h4></a>
40 * <p>Follow this style to write a canonical {@code equals} method:
41 * <pre>
42 *   // Use @Override to avoid accidental overloading.
43 *   &#x0040;Override public boolean equals(Object o) {
44 *     // Return true if the objects are identical.
45 *     // (This is just an optimization, not required for correctness.)
46 *     if (this == o) {
47 *       return true;
48 *     }
49 *
50 *     // Return false if the other object has the wrong type.
51 *     // This type may be an interface depending on the interface's specification.
52 *     if (!(o instanceof MyType)) {
53 *       return false;
54 *     }
55 *
56 *     // Cast to the appropriate type.
57 *     // This will succeed because of the instanceof, and lets us access private fields.
58 *     MyType lhs = (MyType) o;
59 *
60 *     // Check each field. Primitive fields, reference fields, and nullable reference
61 *     // fields are all treated differently.
62 *     return primitiveField == lhs.primitiveField &amp;&amp;
63 *             referenceField.equals(lhs.referenceField) &amp;&amp;
64 *             (nullableField == null ? lhs.nullableField == null
65 *                                    : nullableField.equals(lhs.nullableField));
66 *   }
67 * </pre>
68 * <p>If you override {@code equals}, you should also override {@code hashCode}: equal
69 * instances must have equal hash codes.
70 *
71 * <p>See <i>Effective Java</i> item 8 for much more detail and clarification.
72 *
73 * <a name="writing_hashCode"><h4>Writing a correct {@code hashCode} method</h4></a>
74 * <p>Follow this style to write a canonical {@code hashCode} method:
75 * <pre>
76 *   &#x0040;Override public int hashCode() {
77 *     // Start with a non-zero constant.
78 *     int result = 17;
79 *
80 *     // Include a hash for each field.
81 *     result = 31 * result + (booleanField ? 1 : 0);
82 *
83 *     result = 31 * result + byteField;
84 *     result = 31 * result + charField;
85 *     result = 31 * result + shortField;
86 *     result = 31 * result + intField;
87 *
88 *     result = 31 * result + (int) (longField ^ (longField >>> 32));
89 *
90 *     result = 31 * result + Float.floatToIntBits(floatField);
91 *
92 *     long doubleFieldBits = Double.doubleToLongBits(doubleField);
93 *     result = 31 * result + (int) (doubleFieldBits ^ (doubleFieldBits >>> 32));
94 *
95 *     result = 31 * result + Arrays.hashCode(arrayField);
96 *
97 *     result = 31 * result + referenceField.hashCode();
98 *     result = 31 * result +
99 *         (nullableReferenceField == null ? 0
100 *                                         : nullableReferenceField.hashCode());
101 *
102 *     return result;
103 *   }
104 * </pre>
105 *
106 * <p>If you don't intend your type to be used as a hash key, don't simply rely on the default
107 * {@code hashCode} implementation, because that silently and non-obviously breaks any future
108 * code that does use your type as a hash key. You should throw instead:
109 * <pre>
110 *   &#x0040;Override public int hashCode() {
111 *     throw new UnsupportedOperationException();
112 *   }
113 * </pre>
114 *
115 * <p>See <i>Effective Java</i> item 9 for much more detail and clarification.
116 *
117 * <a name="writing_toString"><h4>Writing a useful {@code toString} method</h4></a>
118 * <p>For debugging convenience, it's common to override {@code toString} in this style:
119 * <pre>
120 *   &#x0040;Override public String toString() {
121 *     return getClass().getName() + "[" +
122 *         "primitiveField=" + primitiveField + ", " +
123 *         "referenceField=" + referenceField + ", " +
124 *         "arrayField=" + Arrays.toString(arrayField) + "]";
125 *   }
126 * </pre>
127 * <p>The set of fields to include is generally the same as those that would be tested
128 * in your {@code equals} implementation.
129 * <p>See <i>Effective Java</i> item 10 for much more detail and clarification.
130 */
131public class Object {
132    /**
133     * Constructs a new instance of {@code Object}.
134     */
135    public Object() {
136    }
137
138    /**
139     * Creates and returns a copy of this {@code Object}. The default
140     * implementation returns a so-called "shallow" copy: It creates a new
141     * instance of the same class and then copies the field values (including
142     * object references) from this instance to the new instance. A "deep" copy,
143     * in contrast, would also recursively clone nested objects. A subclass that
144     * needs to implement this kind of cloning should call {@code super.clone()}
145     * to create the new instance and then create deep copies of the nested,
146     * mutable objects.
147     *
148     * @return a copy of this object.
149     * @throws CloneNotSupportedException
150     *             if this object's class does not implement the {@code
151     *             Cloneable} interface.
152     */
153    protected Object clone() throws CloneNotSupportedException {
154        if (!(this instanceof Cloneable)) {
155            throw new CloneNotSupportedException("Class doesn't implement Cloneable");
156        }
157
158        return internalClone((Cloneable) this);
159    }
160
161    /*
162     * Native helper method for cloning.
163     */
164    private native Object internalClone(Cloneable o);
165
166    /**
167     * Compares this instance with the specified object and indicates if they
168     * are equal. In order to be equal, {@code o} must represent the same object
169     * as this instance using a class-specific comparison. The general contract
170     * is that this comparison should be reflexive, symmetric, and transitive.
171     * Also, no object reference other than null is equal to null.
172     *
173     * <p>The default implementation returns {@code true} only if {@code this ==
174     * o}. See <a href="{@docRoot}reference/java/lang/Object.html#writing_equals">Writing a correct
175     * {@code equals} method</a>
176     * if you intend implementing your own {@code equals} method.
177     *
178     * <p>The general contract for the {@code equals} and {@link
179     * #hashCode()} methods is that if {@code equals} returns {@code true} for
180     * any two objects, then {@code hashCode()} must return the same value for
181     * these objects. This means that subclasses of {@code Object} usually
182     * override either both methods or neither of them.
183     *
184     * @param o
185     *            the object to compare this instance with.
186     * @return {@code true} if the specified object is equal to this {@code
187     *         Object}; {@code false} otherwise.
188     * @see #hashCode
189     */
190    public boolean equals(Object o) {
191        return this == o;
192    }
193
194    /**
195     * Invoked when the garbage collector has detected that this instance is no longer reachable.
196     * The default implementation does nothing, but this method can be overridden to free resources.
197     *
198     * <p>Note that objects that override {@code finalize} are significantly more expensive than
199     * objects that don't. Finalizers may be run a long time after the object is no longer
200     * reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup.
201     * Note also that finalizers are run on a single VM-wide finalizer thread,
202     * so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary
203     * for a class that has a native peer and needs to call a native method to destroy that peer.
204     * Even then, it's better to provide an explicit {@code close} method (and implement
205     * {@link java.io.Closeable}), and insist that callers manually dispose of instances. This
206     * works well for something like files, but less well for something like a {@code BigInteger}
207     * where typical calling code would have to deal with lots of temporaries. Unfortunately,
208     * code that creates lots of temporaries is the worst kind of code from the point of view of
209     * the single finalizer thread.
210     *
211     * <p>If you <i>must</i> use finalizers, consider at least providing your own
212     * {@link java.lang.ref.ReferenceQueue} and having your own thread process that queue.
213     *
214     * <p>Unlike constructors, finalizers are not automatically chained. You are responsible for
215     * calling {@code super.finalize()} yourself.
216     *
217     * <p>Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer
218     * thread.
219     *
220     * See <i>Effective Java</i> Item 7, "Avoid finalizers" for more.
221     */
222    @FindBugsSuppressWarnings("FI_EMPTY")
223    protected void finalize() throws Throwable {
224    }
225
226    /**
227     * Returns the unique instance of {@link Class} that represents this
228     * object's class. Note that {@code getClass()} is a special case in that it
229     * actually returns {@code Class<? extends Foo>} where {@code Foo} is the
230     * erasure of the type of the expression {@code getClass()} was called upon.
231     * <p>
232     * As an example, the following code actually compiles, although one might
233     * think it shouldn't:
234     * <p>
235     * <pre>{@code
236     *   List<Integer> l = new ArrayList<Integer>();
237     *   Class<? extends List> c = l.getClass();}</pre>
238     *
239     * @return this object's {@code Class} instance.
240     */
241    public final native Class<?> getClass();
242
243    /**
244     * Returns an integer hash code for this object. By contract, any two
245     * objects for which {@link #equals} returns {@code true} must return
246     * the same hash code value. This means that subclasses of {@code Object}
247     * usually override both methods or neither method.
248     *
249     * <p>Note that hash values must not change over time unless information used in equals
250     * comparisons also changes.
251     *
252     * <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_hashCode">Writing a correct
253     * {@code hashCode} method</a>
254     * if you intend implementing your own {@code hashCode} method.
255     *
256     * @return this object's hash code.
257     * @see #equals
258     */
259    public native int hashCode();
260
261    /**
262     * Causes a thread which is waiting on this object's monitor (by means of
263     * calling one of the {@code wait()} methods) to be woken up. If more than
264     * one thread is waiting, one of them is chosen at the discretion of the
265     * VM. The chosen thread will not run immediately. The thread
266     * that called {@code notify()} has to release the object's monitor first.
267     * Also, the chosen thread still has to compete against other threads that
268     * try to synchronize on the same object.
269     * <p>
270     * This method can only be invoked by a thread which owns this object's
271     * monitor. A thread becomes owner of an object's monitor
272     * </p>
273     * <ul>
274     * <li>by executing a synchronized method of that object;</li>
275     * <li>by executing the body of a {@code synchronized} statement that
276     * synchronizes on the object;</li>
277     * <li>by executing a synchronized static method if the object is of type
278     * {@code Class}.</li>
279     * </ul>
280     *
281     * @see #notifyAll
282     * @see #wait()
283     * @see #wait(long)
284     * @see #wait(long,int)
285     * @see java.lang.Thread
286     */
287    public final native void notify();
288
289    /**
290     * Causes all threads which are waiting on this object's monitor (by means
291     * of calling one of the {@code wait()} methods) to be woken up. The threads
292     * will not run immediately. The thread that called {@code notify()} has to
293     * release the object's monitor first. Also, the threads still have to
294     * compete against other threads that try to synchronize on the same object.
295     * <p>
296     * This method can only be invoked by a thread which owns this object's
297     * monitor. A thread becomes owner of an object's monitor
298     * </p>
299     * <ul>
300     * <li>by executing a synchronized method of that object;</li>
301     * <li>by executing the body of a {@code synchronized} statement that
302     * synchronizes on the object;</li>
303     * <li>by executing a synchronized static method if the object is of type
304     * {@code Class}.</li>
305     * </ul>
306     *
307     * @throws IllegalMonitorStateException
308     *             if the thread calling this method is not the owner of this
309     *             object's monitor.
310     * @see #notify
311     * @see #wait()
312     * @see #wait(long)
313     * @see #wait(long,int)
314     * @see java.lang.Thread
315     */
316    public final native void notifyAll();
317
318    /**
319     * Returns a string containing a concise, human-readable description of this
320     * object. Subclasses are encouraged to override this method and provide an
321     * implementation that takes into account the object's type and data. The
322     * default implementation is equivalent to the following expression:
323     * <pre>
324     *   getClass().getName() + '@' + Integer.toHexString(hashCode())</pre>
325     * <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_toString">Writing a useful
326     * {@code toString} method</a>
327     * if you intend implementing your own {@code toString} method.
328     *
329     * @return a printable representation of this object.
330     */
331    public String toString() {
332        return getClass().getName() + '@' + Integer.toHexString(hashCode());
333    }
334
335    /**
336     * Causes the calling thread to wait until another thread calls the {@code
337     * notify()} or {@code notifyAll()} method of this object. This method can
338     * only be invoked by a thread which owns this object's monitor; see
339     * {@link #notify()} on how a thread can become the owner of a monitor.
340     * <p>
341     * A waiting thread can be sent {@code interrupt()} to cause it to
342     * prematurely stop waiting, so {@code wait} should be called in a loop to
343     * check that the condition that has been waited for has been met before
344     * continuing.
345     * </p>
346     * <p>
347     * While the thread waits, it gives up ownership of this object's monitor.
348     * When it is notified (or interrupted), it re-acquires the monitor before
349     * it starts running.
350     * </p>
351     *
352     * @throws IllegalMonitorStateException
353     *             if the thread calling this method is not the owner of this
354     *             object's monitor.
355     * @throws InterruptedException
356     *             if another thread interrupts this thread while it is waiting.
357     * @see #notify
358     * @see #notifyAll
359     * @see #wait(long)
360     * @see #wait(long,int)
361     * @see java.lang.Thread
362     */
363    public final void wait() throws InterruptedException {
364        wait(0, 0);
365    }
366
367    /**
368     * Causes the calling thread to wait until another thread calls the {@code
369     * notify()} or {@code notifyAll()} method of this object or until the
370     * specified timeout expires. This method can only be invoked by a thread
371     * which owns this object's monitor; see {@link #notify()} on how a thread
372     * can become the owner of a monitor.
373     * <p>
374     * A waiting thread can be sent {@code interrupt()} to cause it to
375     * prematurely stop waiting, so {@code wait} should be called in a loop to
376     * check that the condition that has been waited for has been met before
377     * continuing.
378     * </p>
379     * <p>
380     * While the thread waits, it gives up ownership of this object's monitor.
381     * When it is notified (or interrupted), it re-acquires the monitor before
382     * it starts running.
383     * </p>
384     *
385     * @param millis
386     *            the maximum time to wait in milliseconds.
387     * @throws IllegalArgumentException
388     *             if {@code millis < 0}.
389     * @throws IllegalMonitorStateException
390     *             if the thread calling this method is not the owner of this
391     *             object's monitor.
392     * @throws InterruptedException
393     *             if another thread interrupts this thread while it is waiting.
394     * @see #notify
395     * @see #notifyAll
396     * @see #wait()
397     * @see #wait(long,int)
398     * @see java.lang.Thread
399     */
400    public final void wait(long millis) throws InterruptedException {
401        wait(millis, 0);
402    }
403
404    /**
405     * Causes the calling thread to wait until another thread calls the {@code
406     * notify()} or {@code notifyAll()} method of this object or until the
407     * specified timeout expires. This method can only be invoked by a thread
408     * that owns this object's monitor; see {@link #notify()} on how a thread
409     * can become the owner of a monitor.
410     * <p>
411     * A waiting thread can be sent {@code interrupt()} to cause it to
412     * prematurely stop waiting, so {@code wait} should be called in a loop to
413     * check that the condition that has been waited for has been met before
414     * continuing.
415     * </p>
416     * <p>
417     * While the thread waits, it gives up ownership of this object's monitor.
418     * When it is notified (or interrupted), it re-acquires the monitor before
419     * it starts running.
420     * </p>
421     *
422     * @param millis
423     *            the maximum time to wait in milliseconds.
424     * @param nanos
425     *            the fraction of a millisecond to wait, specified in
426     *            nanoseconds.
427     * @throws IllegalArgumentException
428     *             if {@code millis < 0}, {@code nanos < 0} or {@code nanos >
429     *             999999}.
430     * @throws IllegalMonitorStateException
431     *             if the thread calling this method is not the owner of this
432     *             object's monitor.
433     * @throws InterruptedException
434     *             if another thread interrupts this thread while it is waiting.
435     * @see #notify
436     * @see #notifyAll
437     * @see #wait()
438     * @see #wait(long,int)
439     * @see java.lang.Thread
440     */
441    public final native void wait(long millis, int nanos) throws InterruptedException;
442}
443