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 33 package 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 * @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 && 63 * referenceField.equals(lhs.referenceField) && 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 * @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 * @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 * @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 */ 131 public class Object { 132 /** 133 * Constructs a new instance of {@code Object}. 134 */ Object()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 */ clone()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 */ internalClone(Cloneable o)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 {@code equals} method</a> 175 * if you intend implementing your own {@code equals} method. 176 * 177 * <p>The general contract for the {@code equals} and {@link 178 * #hashCode()} methods is that if {@code equals} returns {@code true} for 179 * any two objects, then {@code hashCode()} must return the same value for 180 * these objects. This means that subclasses of {@code Object} usually 181 * override either both methods or neither of them. 182 * 183 * @param o 184 * the object to compare this instance with. 185 * @return {@code true} if the specified object is equal to this {@code 186 * Object}; {@code false} otherwise. 187 * @see #hashCode 188 */ equals(Object o)189 public boolean equals(Object o) { 190 return this == o; 191 } 192 193 /** 194 * Called before the object's memory is reclaimed by the VM. This 195 * can only happen once the garbage collector has detected that the 196 * object is no longer reachable by any thread of the 197 * running application. 198 * <p> 199 * The method can be used to free system resources or perform other cleanup 200 * before the object is garbage collected. The default implementation of the 201 * method is empty, which is also expected by the VM, but subclasses can 202 * override {@code finalize()} as required. Uncaught exceptions which are 203 * thrown during the execution of this method cause it to terminate 204 * immediately but are otherwise ignored. 205 * <p> 206 * Note that the VM does guarantee that {@code finalize()} is called at most 207 * once for any object, but it doesn't guarantee when (if at all) {@code 208 * finalize()} will be called. For example, object B's {@code finalize()} 209 * can delay the execution of object A's {@code finalize()} method and 210 * therefore it can delay the reclamation of A's memory. To be safe, use a 211 * {@link java.lang.ref.ReferenceQueue}, because it provides more control 212 * over the way the VM deals with references during garbage collection. 213 * </p> 214 * 215 * @throws Throwable 216 * any exception which is raised during finalization; these are 217 * ignored by the virtual machine. 218 */ finalize()219 protected void finalize() throws Throwable { 220 } 221 222 /** 223 * Returns the unique instance of {@link Class} that represents this 224 * object's class. Note that {@code getClass()} is a special case in that it 225 * actually returns {@code Class<? extends Foo>} where {@code Foo} is the 226 * erasure of the type of the expression {@code getClass()} was called upon. 227 * <p> 228 * As an example, the following code actually compiles, although one might 229 * think it shouldn't: 230 * <p> 231 * <pre>{@code 232 * List<Integer> l = new ArrayList<Integer>(); 233 * Class<? extends List> c = l.getClass();}</pre> 234 * 235 * @return this object's {@code Class} instance. 236 */ getClass()237 public final native Class<? extends Object> getClass(); 238 239 /** 240 * Returns an integer hash code for this object. By contract, any two 241 * objects for which {@link #equals} returns {@code true} must return 242 * the same hash code value. This means that subclasses of {@code Object} 243 * usually override both methods or neither method. 244 * 245 * <p>Note that hash values must not change over time unless information used in equals 246 * comparisons also changes. 247 * 248 * <p>See <a href="{@docRoot}/reference/java/lang/Object.html#writing_hashCode">Writing a correct {@code hashCode} method</a> 249 * if you intend implementing your own {@code hashCode} method. 250 * 251 * @return this object's hash code. 252 * @see #equals 253 */ hashCode()254 public native int hashCode(); 255 256 /** 257 * Causes a thread which is waiting on this object's monitor (by means of 258 * calling one of the {@code wait()} methods) to be woken up. If more than 259 * one thread is waiting, one of them is chosen at the discretion of the 260 * virtual machine. The chosen thread will not run immediately. The thread 261 * that called {@code notify()} has to release the object's monitor first. 262 * Also, the chosen thread still has to compete against other threads that 263 * try to synchronize on the same object. 264 * <p> 265 * This method can only be invoked by a thread which owns this object's 266 * monitor. A thread becomes owner of an object's monitor 267 * </p> 268 * <ul> 269 * <li>by executing a synchronized method of that object;</li> 270 * <li>by executing the body of a {@code synchronized} statement that 271 * synchronizes on the object;</li> 272 * <li>by executing a synchronized static method if the object is of type 273 * {@code Class}.</li> 274 * </ul> 275 * 276 * @see #notifyAll 277 * @see #wait() 278 * @see #wait(long) 279 * @see #wait(long,int) 280 * @see java.lang.Thread 281 */ notify()282 public final native void notify(); 283 284 /** 285 * Causes all threads which are waiting on this object's monitor (by means 286 * of calling one of the {@code wait()} methods) to be woken up. The threads 287 * will not run immediately. The thread that called {@code notify()} has to 288 * release the object's monitor first. Also, the threads still have to 289 * compete against other threads that try to synchronize on the same object. 290 * <p> 291 * This method can only be invoked by a thread which owns this object's 292 * monitor. A thread becomes owner of an object's monitor 293 * </p> 294 * <ul> 295 * <li>by executing a synchronized method of that object;</li> 296 * <li>by executing the body of a {@code synchronized} statement that 297 * synchronizes on the object;</li> 298 * <li>by executing a synchronized static method if the object is of type 299 * {@code Class}.</li> 300 * </ul> 301 * 302 * @throws IllegalMonitorStateException 303 * if the thread calling this method is not the owner of this 304 * object's monitor. 305 * @see #notify 306 * @see #wait() 307 * @see #wait(long) 308 * @see #wait(long,int) 309 * @see java.lang.Thread 310 */ notifyAll()311 public final native void notifyAll(); 312 313 /** 314 * Returns a string containing a concise, human-readable description of this 315 * object. Subclasses are encouraged to override this method and provide an 316 * implementation that takes into account the object's type and data. The 317 * default implementation is equivalent to the following expression: 318 * <pre> 319 * getClass().getName() + '@' + Integer.toHexString(hashCode())</pre> 320 * <p>See <a href="{@docRoot}/reference/java/lang/Object.html#writing_toString">Writing a useful {@code toString} method</a> 321 * if you intend implementing your own {@code toString} method. 322 * 323 * @return a printable representation of this object. 324 */ toString()325 public String toString() { 326 return getClass().getName() + '@' + Integer.toHexString(hashCode()); 327 } 328 329 /** 330 * Causes the calling thread to wait until another thread calls the {@code 331 * notify()} or {@code notifyAll()} method of this object. This method can 332 * only be invoked by a thread which owns this object's monitor; see 333 * {@link #notify()} on how a thread can become the owner of a monitor. 334 * <p> 335 * A waiting thread can be sent {@code interrupt()} to cause it to 336 * prematurely stop waiting, so {@code wait} should be called in a loop to 337 * check that the condition that has been waited for has been met before 338 * continuing. 339 * </p> 340 * <p> 341 * While the thread waits, it gives up ownership of this object's monitor. 342 * When it is notified (or interrupted), it re-acquires the monitor before 343 * it starts running. 344 * </p> 345 * 346 * @throws IllegalMonitorStateException 347 * if the thread calling this method is not the owner of this 348 * object's monitor. 349 * @throws InterruptedException 350 * if another thread interrupts this thread while it is waiting. 351 * @see #notify 352 * @see #notifyAll 353 * @see #wait(long) 354 * @see #wait(long,int) 355 * @see java.lang.Thread 356 */ wait()357 public final void wait() throws InterruptedException { 358 wait(0 ,0); 359 } 360 361 /** 362 * Causes the calling thread to wait until another thread calls the {@code 363 * notify()} or {@code notifyAll()} method of this object or until the 364 * specified timeout expires. This method can only be invoked by a thread 365 * which owns this object's monitor; see {@link #notify()} on how a thread 366 * can become the owner of a monitor. 367 * <p> 368 * A waiting thread can be sent {@code interrupt()} to cause it to 369 * prematurely stop waiting, so {@code wait} should be called in a loop to 370 * check that the condition that has been waited for has been met before 371 * continuing. 372 * </p> 373 * <p> 374 * While the thread waits, it gives up ownership of this object's monitor. 375 * When it is notified (or interrupted), it re-acquires the monitor before 376 * it starts running. 377 * </p> 378 * 379 * @param millis 380 * the maximum time to wait in milliseconds. 381 * @throws IllegalArgumentException 382 * if {@code millis < 0}. 383 * @throws IllegalMonitorStateException 384 * if the thread calling this method is not the owner of this 385 * object's monitor. 386 * @throws InterruptedException 387 * if another thread interrupts this thread while it is waiting. 388 * @see #notify 389 * @see #notifyAll 390 * @see #wait() 391 * @see #wait(long,int) 392 * @see java.lang.Thread 393 */ wait(long millis)394 public final void wait(long millis) throws InterruptedException { 395 wait(millis, 0); 396 } 397 398 /** 399 * Causes the calling thread to wait until another thread calls the {@code 400 * notify()} or {@code notifyAll()} method of this object or until the 401 * specified timeout expires. This method can only be invoked by a thread 402 * that owns this object's monitor; see {@link #notify()} on how a thread 403 * can become the owner of a monitor. 404 * <p> 405 * A waiting thread can be sent {@code interrupt()} to cause it to 406 * prematurely stop waiting, so {@code wait} should be called in a loop to 407 * check that the condition that has been waited for has been met before 408 * continuing. 409 * </p> 410 * <p> 411 * While the thread waits, it gives up ownership of this object's monitor. 412 * When it is notified (or interrupted), it re-acquires the monitor before 413 * it starts running. 414 * </p> 415 * 416 * @param millis 417 * the maximum time to wait in milliseconds. 418 * @param nanos 419 * the fraction of a millisecond to wait, specified in 420 * nanoseconds. 421 * @throws IllegalArgumentException 422 * if {@code millis < 0}, {@code nanos < 0} or {@code nanos > 423 * 999999}. 424 * @throws IllegalMonitorStateException 425 * if the thread calling this method is not the owner of this 426 * object's monitor. 427 * @throws InterruptedException 428 * if another thread interrupts this thread while it is waiting. 429 * @see #notify 430 * @see #notifyAll 431 * @see #wait() 432 * @see #wait(long,int) 433 * @see java.lang.Thread 434 */ wait(long millis, int nanos)435 public final native void wait(long millis, int nanos) throws InterruptedException; 436 } 437