The root object of the Java class

Source: Internet
Author: User

I. Introduction of Object class

Object Full Name Java.lang.object,java.lang The package is used without displaying the import and is automatically imported by the compiler at compile time. The object class is the root of the class hierarchy, and all classes in Java are fundamentally inherited from this class.

The object class is the only class in Java that does not have a parent class. All other classes, including standard container classes, such as arrays, inherit the methods in the object class (all classes implicitly inherit from object, and if you do not explicitly assign a parent class to a class, the compiler adds a parent class object to the class, and if you assign it a parent class, The compiler will not be superfluous).

Ii. behavior of Object

The attributes and behaviors of object are the reflection of the thinking behind the Java language design. The object class has no properties defined, there are 13 methods, and the specific class definition structure is as follows:

1. Class Builder public Object ();

In most cases , Java passes through A shape such as new A (args.). form to create an object that belongs to that type. Where A is the class name, a (args..) That is, the corresponding constructor in this class definition. Objects created in this form are completed through constructors in the class. To embody this attribute, Java stipulates that in the class definition process, for classes that do not define constructors, the default is a parameterless constructor, as the base class for all classes, the object class naturally reflects this attribute, in the source code, does not give the object class constructor definition, but in fact, This constructor is present.

Of course, not all classes are constructed in this way, and it is natural that not all class constructors are public.

2.private static native void Registernatives ();

Registernatives function preceded by the native keyword decoration, java, with the native keyword decorated function shows that the implementation of the method is not in Java to complete, but by the C + + to complete, and was compiled into a. dll, called by Java. The concrete implementation of the method in the DLL file, for different platforms, its specific implementation should be different. With native modification, which means the operating system, this method needs to be provided and Java itself needs to be used. Specific to the registernatives () method itself, its main role is to map the C + + method in the Java native method, the implementation of the method named decoupling.

In this case, one might ask, registernatives () modifier is private, and does not execute, how does the function reach? In fact, in Java source code, the declaration of this method followed by a block of static blocks:

1 private static native void Registernatives (); 2 static {3     registernatives (); 4}

3.protected native Object clone () throws Clonenotsupportedexception;

See, the Clone () method is also a method that is declared as native, so we know that the Clone () method is not the native method of Java, the concrete implementation is a C/s is completed. Clone English translates to "cloning", which is intended to create and return a copy of this object. Image point understanding, there is a Cruze, you look good, want an identical. You can call this method to change the exact same Cruze out of the magic. Configuration, looks the same. But from now on, if the original Cruze had a new decoration, it had nothing to do with this Cruze you cloned. The object you cloned is exactly what you have done with the cloned Cruze. The Java term is expressed as: theclone function returns a reference to a new clone-out object that occupies a different heap space than the original object.

After you understand the meaning of clone, take a look at the Clone () function object to do this cloning operation.

Let's take a look at the following example:

1 package com.corn.objectsummary; 2  3 import Com.corn.Person; 4  5 public class Objecttest {6  7 public     static void Main (string[] args) {8
    9         Object O1 = new Object ();/The         Method Clone () from the type object was not visible11         object clone = O1 . Clone ();     }13 14}

The example is simple, in the main () method, after new a Oject object, you want to directly invoke the object's Clone method to clone an object, but there is an error message: "The method Clone () from the type object was not visible"

Why? As a hint, the first reaction is that the Oject object defined in the Objecttest class cannot access its clone () method. Back to the definition of the Clone () method in the object class, you can see that it is declared as protected, and the problem is on top of that, and the protected decorated property or method means that the subclass of the same package or different packages can be accessed. Obviously, the object class and the Objecttest class are in different packages, but Objecttest inherits from object, which is a subclass of the object class, so now there is no way to access the protected method through the object reference in the subclass, because "Sub-classes in different packages can be accessed" is not understood correctly.

"Subclasses in different packages can be accessed" means that when two classes are not in the same package, the members (properties/methods) of the parent class that are decorated with protected can be accessed by inheriting from within the child class of the parent class and by the Master (caller) as a reference to the subclass. Inside a subclass, the master is a reference to the parent class and cannot access the members of this protected adornment. (except Super keyword)

Thus, the above example is changed to the following form, we found that can be compiled normally:

1 package com.corn.objectsummary; 2  3  4 public class Objecttest {5  6 public     static void Main (string[] args) {7         objecttest ot1 = new Ob Jecttest (); 8  9         try {Ten             objecttest Ot2 = (objecttest) ot1.clone ();         catch (Clonenotsupportedexception e) {12             //TODO auto-generated catch block13             e.printstacktrace ();         }15     }16 17}

Yes, because the keynote at this point is already a reference to the subclass.

The above code throws "Java.lang.CloneNotSupportedException" during the run, indicating that the clone () method is not executed correctly, and the reason for the problem is in the syntax in Java:

The correct invocation of clone () is to implement the Cloneable interface, which throws a Clonenotsupportedexception exception if the Cloneable interface is not implemented and the subclass directly calls the Clone () method of the object class.

The Cloneable interface is only a representation interface, and the interface itself does not contain any methods that indicate that Object.clone () can be invoked by a legitimate quilt class reference.

Therefore, the above code is changed to the following form, you can correctly specify the clone () method to achieve cloning.

1 package com.corn.objectsummary; 2  3 public class Objecttest implements cloneable {4  5 public     static void Main (string[] args) {6  7         Ob Jecttest ot1 = new Objecttest (); 8  9         try {Ten             objecttest Ot2 = (objecttest) ot1.clone ();             System.out.println ("Ot2:" + ot2);         catch (Clonenotsupportedexception e) {             //TODO auto-generated catch block14             e.printstacktrace ();     }17 18}

More knowledge about Java cloning/replication will give you a special post.

4.public Final native class<?> getclass ();

GetClass () is also a native method that returns the class object/Runtime class object class<?> of this object. The effect is the same as Object.class.

First, the concept of "class object" is explained: In Java, a class is an abstraction and description of an instance that has the same set of characteristics or behavior, and the object is a concrete instance of the feature or behavior described by this class. As a class of conceptual hierarchy, it also has some common characteristics, such as having the class name, loading by the ClassLoader, having the package, having the parent class, properties and methods, and so on. Thus, in Java, there is a class, classes, to describe the other classes have these features, so from this point of view, the class itself is a class object. This is referred to as the "class object", which is distinguished from the object in the regular sense.

The main concern here is the reflection knowledge in Java, and the related knowledge of reflection will also give the relevant blog post.

5.public boolean equals (Object obj);

= = and equals are often used in Java, and we all know the difference between = = and equals:

= = indicates that the value of the variable is done the same (for the underlying type, the value is stored in the address, and the reference type stores the address pointing to the actual object);

equals represents the exact same content of an object, where the content refers to the object's characteristics/properties.

In fact, the above statement is not rigorous, more than just common in the string class. First look at the definition of the Equals () method in the object class:

1 public boolean equals (Object obj) {2     return (this = = obj); 3}

Thus, the object native Equals () method is called by = =, and = = has the same meaning. So why do you define this equals () method?

The correct understanding of the Equlas () method should be: Determine whether two objects are equal. So what are the rulers that judge the equality of objects?

As above, in the object class, this ruler is = =. Of course, this ruler is not fixed, and other classes can redefine the meaning of the ruler as they are actually needed. This ruler meaning is redefined in the string class based on whether the contents of the strings are equal. This can increase the flexibility of the class's functional and actual coding. Of course, if the custom class does not rewrite the Equals () method to redefine this ruler, then the default will be the Equals () of its parent class until the object base class.

The actual business requirements for the following scenario, for the user bean, are known by the actual business requirements when the attribute UID is the same as the same user, that is, two user objects are equal. You can override equals to redefine the ruler for which the user object is equal.

1 package com.corn.objectsummary; 2  3 public class User {4  5     private int uid, 6     private String name; 7     private int age; 8  9     Pub LIC int Getuid () {Ten         return uid;11     }12 public     void setUid (int uid) {         this.uid = uid;15}16     17
    protected string GetName () {         name;19}20 public     void SetName (string name) {         THIS.name = name;23     }24 public     int Getage () {+         return age;27     }28-Public     void Setage (int a GE) {         this.age = age;31     }32 @Override34 public     boolean equals (Object obj) {+         if (obj = = Nu ll | | ! (obj instanceof User)) {             false;37 return         }38         if ((User) obj). Getuid () = = This.getuid ()) {         true;40}41         return false;42     } 43}
1 package com.corn.objectsummary; 2  3 public class Objecttest implements cloneable {4  5 public     static void Main (string[] args) {6         User u1 = new User (); 7         U1.setuid (111), 8         u1.setname ("Zhang San"), 9         User U2 = New user (),         U2.setuid (111), U2.setname         (" Zhang Sanfeng ");         System.out.println (U1.equals (U2));//return TRUE15     }16 17}

Objecttest print True, because the user class definition overrides the Equals () method, which is very good to understand, it is likely that Zhang is a nickname, Zhang Sanfeng is its name, judge whether the two people are not the same person, then only to determine the UID is the same.

Overriding the Equals method as on the surface seems to be possible, but it is not. Because it destroys the conventions in Java: overriding the Equals () method must override the Hascode () method.

6.public native int hashcode ();

The Hashcode () method returns an integer that represents the hash code value of the object.

Hashcode () has the following conventions:

1). During the Java application Program execution, when the Hashcode () method is called multiple times for the same object, the hash code returned is the same, provided that the ruler information used to compare the object to equals is not modified. The hash code returned by the Hashcode () of the same object does not need to be consistent at the time of execution of the Java application to another execution;

2). If two objects are equal (by calling the Equals () method), then the hash code returned by the two object calls Hashcode () must also be equal;

3). Conversely, two object calls Hascode () return a hash code equal, and the two objects are not necessarily equal.

That is, the strict mathematical logic is represented as: two objects equal <=> equals () equal = = Hashcode () equal. Therefore, overriding the Equlas () method must override the Hashcode () method to ensure that the logic is strictly valid, and can infer that: Hascode () is unequal and equals () is unequal <=> two objects are not equal.

There may be a question here: since the only condition that compares two objects for equality (and also the yell condition) is equals, why make a hashcode () and make such a pact that it's so troublesome?

In fact, this is mainly embodied in the role of the Hashcode () method, which is mainly used to enhance the performance of the hash table.

In the collection class, set for example, when adding an object, you need to determine if an existing collection already has an object equal to this object, and if there is no Hashcode () method, you need to traverse the set one at a time and use the Equals () method to determine whether two objects are equal. The time complexity of this algorithm is O (n). By means of the Hascode method, the hash code of the object to be newly added is computed, and then the position of the object is computed based on the hash algorithm, and the object can be judged directly at this position. (Note: The bottom of set is implemented by the principle of map)

It is necessary to correct an understanding error: The object's Hashcode () returns not the physical memory address where the object resides. Not even the logical address of the object, Hashcode () the same two objects, not necessarily equal, in other words, two objects that are not equal, the hash code returned by Hashcode () may be the same.

Therefore, after overriding the Equals () method in the preceding code, you need to override the Hashcode () method.

 1 package com.corn.objectsummary; 2 3 public class User {4 5 private int UID, 6 private String name; 7 private int age; 8 9 public int g     Etuid () {uid;11}12, public void setUid (int uid) {this.uid = uid;15}16 17 Protected string GetName () {name;19}20 public void SetName (string name) {This.nam         E = name;23}24 public int getage () {age;27}28, public void Setage (int. age) {30 This.age = age;31}32 @Override34 public boolean equals (Object obj) {(obj = = NULL | |!) (             obj instanceof User) {false;37}38 if ((User) obj. getuid () = = This.getuid ()) {39         Return true;40}41 return false;42}43 @Override45 public int hashcode () {46 int result = 17;47 result = * result + this.getuid (); return result;49}50}

Note: result*31 is present in the rewrite of the above hashcode () because result*31 = (result<<5)-result. The reason for choosing 31 is that the left-shift operation and the subtraction computation are much more efficient than the multiplication operation. Of course, you can also choose a different number.

7.public String toString ();

The ToString () method returns the string representation of the object. First look at the specific method body in object:

1 public String toString () {2    return getclass (). GetName () + "@" + integer.tohexstring (Hashcode ()); 3}

The ToString () method is believed to be commonly used, even if it is not explicitly called, but when we use SYSTEM.OUT.PRINTLN (obj), the interior is also implemented by ToString ().

GetClass () Returns the object's class object, GetClassName () returns the name of the class object (with the package name) as a string. Integer.tohexstring (Hashcode ()) returns the string representation of this hash code as a 16-bit unsigned integer as an argument to the object's hash code.

As the hash code for U1 in the previous example is 638, the corresponding 16 binary is 27e, and the result of calling the ToString () method is: [email protected].

Therefore: ToString () is determined by the object's type and its hash code, and the same type, but not equal, two objects called the ToString () method may return the same result.

8/9/10/11/12. Wait (...)/notify ()/Notifyall ()

A talk about Wait (...)/notify () | Notifyall () Several methods, the first thought is the thread. Indeed, these methods are primarily used for collaboration between Java multithreading. Look at the main meanings of these methods first:

Wait (): Call this method where the current thread waits until the Notify ()/notifyall () method of this method's keynote (an object) is raised on another thread.

Wait (long timeout)/wait (long timeout, int nanos): Call this method on the current thread to wait until the notisfy ()/notisfyall () method of this method's keynote (an object) is raised on another thread, or exceeds the specified time-out amount.

Notify ()/notifyall (): Wakes up a single thread/all threads waiting on this object monitor.

Wait (...)/notify () | Notifyall () is generally used as a companion. Let's look at a simple example:

 1 package Com.qqyumidi; 2 3 public class ThreadTest {4 5/** 6 * @param args 7 */8 public static void Main (string[] args) { 9//TODO auto-generated method stub10 myrunnable r = new myrunnable (); thread t = new Thread (r) , T.start (), synchronized (r) {try {System.out.println ("main thread Wait for the T thread to finish "); r.wait (); System.out.println (" Awakened by notity to continue execution "); catch (I                 Nterruptedexception e) {//TODO auto-generated catch Block20 e.printstacktrace (); 21 System.out.println ("Main thread wanted to wait, but was accidentally interrupted");}23 System.out.println ("Thread T performs the add result" + r.gettotal ());}25}26}27-Class Myrunnable implements Runnable {$ private int total;30 @Ov          Erride32 public void Run () {A//TODO auto-generated method stub34 synchronized (this) {35   System.out.println ("Thread name is:" + thread.currentthread (). GetName ()); N for (int i = 0; I < 10; i++) {PNS Total + = i;38}39 notify (); System.out.println ("Execute Notif after synchronous generation The code block can still continue to execute until ");}42 System.out.println (" The timing of executing the Notif and outside the synchronization block depends on thread scheduling ");}44 public int Gettotal () {return total;47}48}

The result of the operation is:

1 main thread waits for the t thread to finish executing the 2 thread name is:thread-03 execution Notif after the synchronization code block can still continue execution until 4 execution Notif and the timing of code execution outside the synchronization code block depends on thread scheduling  // This line output location has a specific JVM thread scheduling decision, it is possible that the last execution of 5 is notity wake up to continue executing 6 thread t to perform the add result 45

Since it is acting on multi-threading, why is the object the base class has the method? The reason is that any object can theoretically be considered a listener in thread synchronization, and wait (...) The/notify () |notifyall () method can only be used in a synchronous code block.

From the output of the above example, the following conclusions can be drawn:

1. Wait (...) After the method call, the thread will block immediately, and the lock in the synchronization code block that it holds is appropriate until it is awakened or timed out or interrupted and retrieved to the lock before continuing execution;

2. After the Notify ()/notifyall () method call, its thread does not immediately release the lock held until the code in its synchronized code block executes, releasing the lock, so that if it has code after synchronizing the code block, its execution depends on the thread dispatch of the JVM.

In Java source code, you can see that the wait () is defined as follows:

1 public  final void Wait () throws Interruptedexception {2      wait (0); 3  }

And the wait (long timeout, int Nanos) method definition internally is essentially done by calling wait (long timeout). And wait (long timeout) is a native method. Therefore, wait (...) Methods are essentially native implementations.

The Notify ()/notifyall () method is also the native method.

Java threads have a lot of knowledge points, is a relatively large and important knowledge points. Later, there will be blog post specifically for Java multithreading to make a detailed summary. No longer described here.

protected void Finalize ();

The Finalize method is primarily related to the Java garbage collection mechanism. First, let's take a look at the specific definition of the finalized method in object:

1 protected void Finalize () throws Throwable {}

We find that the Finalize method in the object class is defined as an empty method, why is it so defined? What is the timing of the Finalize method's invocation?

First, the Finalize method defined in object indicates that each object in Java will have a finalize behavior, which is invoked when the JVM prepares to garbage reclaim the memory space occupied by the image. As you can see, this method is not called by us (although it is possible to invoke it proactively, at this point it is no different from other custom methods).

Java Summary Article series: Java.lang.Object

Three, object and objects

Object is the base class for all classes in Java and is located in the Java.lang package. Objects is a tool class for Object, located in the Java.util package. It only appears from jdk1.7, which is not inherited by the final modifier, and has a private constructor. It consists of a number of static and practical methods, either null-save (null pointer-safe) or null-tolerant (tolerant of null pointers), used to calculate the hashcode of an object, the string representation of the returned object, and a comparison of two objects.

As the Objects.equals method has made a non-null judgment, it does not throw a null pointer exception, it is Null-save null pointer security, and can also simplify the code.
The source code is as follows:
[Java] View plain copy
public static Boolean Equals (object A, object B) {
return (A = = b) | | (A! = null && a.equals (b));
}

The root object of the Java class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.