1. Brief introduction of Object

The Object class is the Root node of all class hierarchies. As the superclass of all classes, including arrays, it also implements the methods of this class.

So there’s a common saying in Java that everything is an object, and it’s not wrong.

1. Explicit extension

Conclusion the validation

Since Object is the parent of all classes, there is no need to explicitly add inheritance, and Each01 will prompt you to remove redundancy at compile time.

public class Each01 extends Object {
    public static void main(String[] args) {
        System.out.println(new Each01().hashCode()+";"+newObjEa02().hashCode()); }}class ObjEa02 {}
class ObjEa03 extends ObjEa02{}
Copy the code

Here Each01 and ObjEa02 Object instances both have the Object class hashCode method, here is the verification of the existing conclusion.

Compile the file

To see how the bytecode files are loaded from the JVM compilation level, use the javap -c command to view the compiled files. Note the Jdk version 1.8.

javap -c Each01.class
Compiled from "Each01.java"
public class com.base.object.each.Each01 {
  public com.base.object.each.Each01();
    Code:
       0: aload_0
       1: invokespecial #1 // Method java/lang/Object."<init>":()V
       4: return
}

javap -c ObjEa02.class 
Compiled from "Each01.java"
class com.base.object.each.ObjEa02 {
  com.base.object.each.ObjEa02();
    Code:
       0: aload_0
       1: invokespecial #1 // Method java/lang/Object."<init>":()V
       4: return
}

javap -c ObjEa03.class 
Compiled from "Each01.java"
class com.base.object.each.ObjEa03 extends com.base.object.each.ObjEa02 {
  com.base.object.each.ObjEa03();
    Code:
       0: aload_0
       1: invokespecial #1 // Method com/base/object/each/ObjEa02."<init>":()V
       4: return
}
Copy the code

Invokespecial command: you can view the instructions in the official documentation of the Jvm, call the instantiation method, and the initialization method call of the parent class, etc. Here, through the hierarchy of the three classes, again shows that the Object superclass does not need explicit inheritance, even if explicitly declared, but after compiling the source code will still remove the redundancy.

2. References and objects

The following process is commonly referred to as: Creating an object;

Object object = new Object() ;
Copy the code

Detail description: declare the object reference object; Create objects with the new keyword and initialize them based on the default constructor; Refers the object reference object to the created object.

This can be understood in terms of the Jvm runtime flow, so that when an object loses all references, it is marked as a garbage object and cleaned up when the garbage collector runs.

Accepts a reference to an object of any data type

Since Object is the superclass of all objects in Java, according to the characteristics of inheritance relationship and upward transformation mechanism, Object can accept the reference of objects of any data type. For example, in the collection container or the parameter passing process, Object can be used when the Object type is uncertain:

public class Each02 {
    public static void main(String[] args) {
        // Upward transition
        Object obj01 = new Each02Obj01("java"); System.out.println(obj01);// Downward transition
        Each02Obj01 each02Obj01 = (Each02Obj01)obj01;
        System.out.println("name="+each02Obj01.getName()); }}class Each02Obj01 {
    private String name ;
    public Each02Obj01(String name) { this.name = name; }
    @Override
    public String toString(a) {
        return "Each02Obj01{" +"name='" + name +'} ';
    }
    public String getName(a) { returnname; }}Copy the code

Here is to emphasize the upward transition process:

Object obj01 = new Each02Obj01("java");Copy the code

By analyzing the flow above, we create a parent class that refers to obj01 and points to the Each02Obj01 object, so we call the toString method of the child class when we output it.

Second, basic methods

1, getClass

Get the instance class of an object while the program is running, so that you can get detailed structural information and operate on it:

public final nativeClass<? > getClass();Copy the code

This method has many applications in generics, reflection, dynamic proxy and other mechanisms.

2, the toString

Object provides a hash representation of the class name and an unsigned hexadecimal value. Subclasses usually override this method to return an unambiguous string:

public String toString(a) {
    return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
Copy the code

In Java, when an object is printed, string.valueof is converted to a String. The underlying method is still the object’s toString method:

public void println(Object x) {
    String s = String.valueOf(x);
}
public static String valueOf(Object obj) {
    return (obj == null)?"null" : obj.toString();
}
Copy the code

Equals and hashCode

  • Equals: Determines whether two objects are equal;
  • HashCode: Returns the hash value of an object;
public native int hashCode(a);
public boolean equals(Object obj) {
    return (this == obj);
}
Copy the code

The equals method needs to consider actual scenarios and policies. For example, the common identity ID assigned to a citizen after registration cannot be changed, but the name can be changed. Then there may be scenarios like this:

EachUser eachUser01 = new EachUser(1."A"); EachUser eachUser02 =new EachUser(1."B");class EachUser {
    private Integer cardId ;
    private String name ;
}
Copy the code

In the case of the program itself, this does create two objects, but in the case of the scene, it does describe the same person, so you can define a comparison rule in equals to treat the same object if the ID is the same:

@Override
public boolean equals(Object obj) {
    if(obj ! =null){
        EachUser compareObj = (EachUser)obj ;
        return this.cardId.intValue()==compareObj.cardId ;
    }
    return Boolean.FALSE ;
}
Copy the code

Note also the difference between the value type and the reference type, and return false if a null comparison occurs.

It is common to override both methods in subclasses, as has been done in the design of collection containers.

4, Thread related

  • Wait: the thread enters the waiting state and does not compete for the lock object
  • Notify: Randomly notifies a thread waiting on the object;
  • NotifyAll: Wakes up all waiting threads on the object;
public final native void wait(long timeout) throws InterruptedException;
public final native void notify(a);
public final native void notifyAll(a);
Copy the code

Note here: the native keyword modification method, namely calls the native function, which is often said to be based on the C/C++ implementation of the local method, in order to improve the efficiency of interaction with the system level and reduce the complexity of interaction.

5, clone

Returns a copy of the current object:

protected native Object clone(a) throws CloneNotSupportedException;
Copy the code

The detailed rules for this method are extremely complex, so note the following core points:

  • Objects must implement the Cloneable interface to be cloned.
  • Data types: value type, String type, reference type;
  • The difference between deep and shallow copy and its corresponding implementation process;
  • In a complex wrapper type, a combination of different variable types;

6, finalize

When the garbage collector confirms that there is no reference on the object, the Finalize method is called, which clears memory to free resources:

protected void finalize(a) throws Throwable {}Copy the code

Normally a subclass will not override this method unless there is some other necessary resource cleaning action in the subclass.

Life cycle

1. Scope

The instance object of Each05Obj01 cannot be accessed after the following main method is executed because the reference to each05 is missing:

public class Each05 {
    public static void main(String[] args) {
        Each05Obj01 each05 = new Each05Obj01 (99); System.out.println(each05); }}Copy the code

The problem here is that the lost reference makes the object unreachable, but the object may still exist at this point without freeing up memory.

2. Garbage collection mechanism

Objects created by Java with new create memory space in the heap, and when objects lose all references they are marked as garbage and recycled.

Here are a few key points:

  • The garbage collector in the Jvm monitors the objects created;
  • When the object is judged to have no reference, the cleanup action is performed.
  • After object cleanup is complete, the memory space is reorganized.

There is a difficult concept to understand, that is, the object does not exist the judgment of reference, also known as the reachable analysis algorithm: based on the object to the root object reference chain is reachable to determine whether the object can be recycled; Gc-roots collection of root references can also be interpreted as a collection of living objects. (See JVM series)

Through the analysis of Object objects, combined with all aspects of Java mechanism and design, you can go to some so-called programming ideas.

Source code address

GitEE address https://gitee.com/cicadasmile/java-base-parent Wiki, https://gitee.com/cicadasmile/butte-java-note/wikisCopy the code