Understand the basic Object classes in Java

Keywords: Java Interview Programmer architecture

1, Object description

Source code note: the Object class is the Root node of the hierarchical relationship of all classes. As the superclass of all classes, including arrays, it also implements the methods of this class. Note that what is said here is very clear, referring to the class level.

Therefore, there is a common saying in Java that everything is an object, which is not unreasonable.

1. Explicit extension

Conclusion verification

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

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

Here, both Each01 and obja02 Object instances have the hashCode method in the Object class. Here, the existing conclusions are verified.

Compiled file

Then, from the JVM compilation level, see how the bytecode file is loaded. Use the javap -c command to view the compiled file. Note that 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
}

invokespecial command: you can view the instruction description, calling instantiation methods, and parent class initialization method calls in the official Jvm documents. Here, through the hierarchical relationship of the three classes, it is explained again that the Object superclass does not need explicit inheritance. Even if it is explicitly declared, the redundancy of the compiled source code will still be removed.

2. References and objects

The following process is usually called: create an object;

Object object = new Object() ;

Detailed description: declare the object reference object; Create an object through the new keyword and initialize it based on the default construction method; Point the object reference object to the created object.

This can be understood based on the Jvm running process, so once an object loses all references, it will be marked as a garbage object and cleaned up when the garbage collector runs.

Accepts references to objects 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 references to objects of any data type. For example, in the collection container or parameter transfer process, Object can be used when the Object type is uncertain:

public class Each02 {
    public static void main(String[] args) {
        //  Upward transformation
        Object obj01 = new Each02Obj01("java") ;
        System.out.println(obj01);
        //  Downward transformation
        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() {
        return "Each02Obj01{" +"name='" + name +'}';
    }
    public String getName() { return name; }
}

Here we would like to emphasize this upward transformation process:

Object obj01 = new Each02Obj01("java") ;

Through the above process analysis, a parent class reference obg01 is created here and points to the child class Each02Obj01 object. Therefore, when outputting, the toString method of the child class is called.

2, Basic method

1,getClass

Obtain the instance class of the object when the program is running, and then you can obtain detailed structure information and operate:

public final native Class<?> getClass();

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

2,toString

Returns the string description of the Object. The Object provides a combination of the class name and the unsigned hexadecimal hash value. In order to return a string with clear information, the subclass usually overrides the method:

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

In Java, when printing an object, String.valueOf will be converted to a string. The bottom layer of this method is still the toString method of the object:

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

3. equals and hashCode

  • equals: judge whether two objects are equal;

  • hashCode: returns the hash code value of the object;

public native int hashCode();
public boolean equals(Object obj) {
    return (this == obj);
}

The equals judgment method needs to consider the actual scenarios and strategies. For example, the common identity ID assigned after citizen registration cannot be modified, but the name can be modified, so there may be such scenarios:

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

From the perspective of the program itself, this is indeed creating two objects, but in the scenario, this is really describing the same person, so at this time, you can define a comparison rule in the equals method. If the ID s are the same, it will be regarded as the same object:

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

Pay attention to the difference between value type and reference type. If null comparison occurs, return false.

These two methods are usually overridden in subclasses at the same time, which has been reflected incisively and vividly in the design of collection containers.

4. thread correlation

  • wait: the thread enters the waiting state and will not compete for lock objects

  • Notify: randomly notify a thread waiting on the object;

  • notifyAll: wake up all waiting threads on the object;

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

Note here: the method modified by the native keyword calls the native function, that is, the local method based on C/C + + implementation, so as to improve the interaction efficiency with the system level and reduce the interaction complexity.

5,clone

Returns a copy of the current object:

protected native Object clone() throws CloneNotSupportedException;

The detailed rules of this method are extremely complex, and the following core points should be paid attention to:

  • Objects must implement clonable interface before they can be cloned;

  • Data type: value type, String type, reference type;

  • The difference between deep and shallow copy and the corresponding implementation process;

  • In complex packaging types, different variable types are combined;

6,finalize

When the garbage collector confirms that there is no reference on the object, it will call the finalize method, that is, clean up memory and free resources:

protected void finalize() throws Throwable { }

Typically, subclasses do not override this method unless there are some other necessary resource cleanup actions in the subclass.

3, Life cycle

1. Scope

After the execution of the following main method, the instance object of Each05Obj01 can no longer be accessed because the reference each05 of the object is lost:

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

There will be a problem here. The object cannot be accessed due to the loss of references, but the object may still exist at this time and does not release the occupation of memory.

2. Garbage collection mechanism

Java objects created through new will open up memory space in the heap. When the object loses all references, it will be marked as garbage objects and then recycled;

Here are the following key points:

  • The garbage collector in the Jvm monitors the created objects;

  • When it is judged that there is no reference to the object, the cleanup action will be executed;

  • After object cleaning, the memory space will be rearranged;

There is a difficult concept to understand here, that is, the judgment that there is no reference to the object, that is, the commonly known reachability analysis algorithm: judge whether the object can be recycled based on whether the reference chain from the object to the root object is reachable; GC roots root refers to a collection, which can also be understood as a collection of living objects. (see JVM series for details)

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

Same series:   List analysis | Map analysis | IO stream core | Dynamic agent | object-oriented

4, Source code address

GitEE·address
https://gitee.com/cicadasmile/java-base-parent
Wiki·address
https://gitee.com/cicadasmile/butte-java-note/wikis

Posted by d_barszczak on Mon, 29 Nov 2021 00:23:38 -0800