Common methods of Object class in Java

What is the Object class?

The root class of the class hierarchy. Each class uses Object as the superclass (parent class).

getClass

public final Class getClass()

the current class as Class

Returns: a Class object representing the runtime class of this object.

There is a method in the Class class: public String getName()

Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object as a String.

Run the program:

public class Dc {
    public static void main(String[] args) {
        Rmb a = new Rmb();
        Class c = a.getClass();
        System.out.println(c);
        System.out.println(c.getName());
        System.out.println(a.getClass().getName());
    }

}

operation result:

class org.westos.Rmb

org.westos.Rmb

org.westos.Rmb


hashCode

public int hashCode()

Returns the hash code value of this object

Hash code value: generally implemented by converting the internal address of the object to an integer.

equals

public boolean equals(Object obj)

Indicates whether some other object is "equal" to this object.

== is a comparison of address values ​​for reference variables

According to the normal situation: the two objects actually executed at the bottom of the equals method are compared at == (it is recommended to override this method)

Note : When this method is overridden, it is often necessary to override the hashCode method to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes .


public String toString()

Directly output the object name: the toString() in Object is actually executed, and the output full class name@hexadecimal data

等于:getClass().getName() + '@' + Integer.toHexString(hashCode())

It is recommended that all subclasses override this method.

If you don't want toString() to directly output an address value (the address value of the object), you need to rewrite toSring() in Object. In general, it can be automatically generated    

clone

protected Object clone()

                throws CloneNotSupportedException

Creates and returns a copy of this object (equivalent to a copy)

The clone method of the Object class performs a specific copy operation. First, if the class of this object cannot implement the interface Cloneable, a CloneNotSupportedException will be thrown.

Note : All arrays are considered to implement the interface Cloneable

finalize

protected void finalize()

                 throws Throwable

This method is called when the gc starts and the object is collected. In fact, gc can recycle most of the objects (all new objects can be handled by gc, and under normal circumstances, we will not use methods other than new to create objects), so there is generally no need for programmers to implement finalize.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324850400&siteId=291194637