java foundation Object class



1. getClass method

2. equals method

3. hashCode() method

4. toString method

5. clone method

6. Grammar sugar: automatic packing and unpacking

The Object class is the root of all Java class inheritance systems. All Java classes, including arrays, inherit from the Object class. There are 12 methods in the Object class. One is private, two are protected, and the other nine are public. The common methods are listed as follows:



Class getClass()

Returns a class object when the object is running

int hashCode()

Returns the hash value of the object

boolean equals(Object obj)

Compare two objects for equality

String toString()

Returns the string representation of the object

Object clone()

Implement object replication



1. getClass method

Returns the class object of an object at runtime. When a class is loaded into a virtual machine, it will generate a java.lang.Class Object, through which you can access all kinds of data of this class in the method area.

    Object object = new Object();

    //Returns the Class object of the corresponding Class of the current object
    System.out.println(object.getClass());//class java.lang.Object

    ObjectCase objectCase1 = new ObjectCase();

    ObjectCase objectCase2 = new ObjectCase();
    // Class objects of ObjectCase are returned


2. equals method

The equals method compares two objects for equality. The implementation of the Object class is as follows. By default, the addresses of the two objects are compared.

public boolean equals(Object obj){
    return (this==obj);


Some classes, such as Integer, String, and Date, override the equals method. Judge whether two objects are equal by comparing the values of two objects. The equals method in the String class is implemented as follows: first compare whether it is the same object, and then compare whether the values are equal if it is not the same object.

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
            return true;
    return false;

be careful:

  1. ==Variables of the basic data type are compared for equality. For reference variables, their memory addresses are compared. The equals method is used to compare reference variables. The default implementation is to call = = compare memory address, which is the same as the result returned by = = but for some classes that override the eqauls method, the results returned by the equals method and = = method are not guaranteed to be the same.
  2. After overriding the equals method, you must override the hashCode method to ensure that the hashcodes of two objects with equal eqauls are equal. Otherwise, this class cannot work with hash based collections, such as HashMap, HashSet, and HashTable
  3. Overriding the equals method must comply with the general conventions of the equals method, otherwise the classes that depend on these conventions, such as list and map in the collection class, may not work properly. (it is recommended to carefully refer to the relevant conventions when overriding the eqalus method)
  • Reflexivity: for any non null reference value x, x.equals(x) needs to return true
  • Symmetry: for any non null reference value x, y, when x.equals(y) returns true, y.equals(x) must also return true
  • Transitivity: for any non null reference value x, y, Z, when x.equals(y) returns true and y.equals(z) returns true, x.equals(z) must also return true
  • Consistency: for any non null reference value x, y, as long as the information used in the equals comparison in the object is not modified, x.equals(y) will return true or false consistently many times
  • Non Emptiness: x.equals(null) must return false for any non null reference value x

Refer to Article 8 of effectiveness Java


3. hashCode() method

The hashCode method returns the hash value of the object. The default implementation of the hash value is different in different JVM s. Some return the storage address, but some return the value associated with the storage address.

For the hashCode method, you need to follow the conventions of the Object class for the hashCode method. In the javaSE specification, it is as follows:

  • During the execution of the application, as long as the information affected by the comparison operation of the equals method of the object is not modified, the hashCode method must return the same integer every time it is called multiple times. During multiple executions of the same application, the returned certificates of each call may be inconsistent
  • If two objects are equal according to the equals method comparison, the hashCode method return of the two objects must return the same integer
  • If two objects are not equal according to the equals method, the hashCode method of these two objects does not have to produce the same integer
static void hashCodeTest(){
    Object o1 = new Object();

    //The Integer class overrides the hashCode method, and the generated hash value is the basic value of the Integer object
    Integer i1 = 300;
    Integer i2 =300;
    //The String class also overrides the hashCode method to ensure that objects with equal values return the same hashCode value
    String s1 = "abc";
    String s2 = "abc";


Refer to Article 9 of effect Java


4. toString method

The toString method implemented by default for the Object class is as follows. It returns the class name + @ + hash value

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


5. clone method

The clone method is a potected method, indicating the cloning of objects.

Usage: since the clone method is protected, the subclass needs the implements clonable interface, overriding the clone method and declaring it as public before it can be called. Example:

public class People implements Cloneable{
    int a;
    ParentClass parentClass;

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
static void cloneTest(){
    People p1 = new People();
    ParentClass parentClass = new ParentClass(3);
    p1.parentClass = parentClass;
        People p2 = (People) p1.clone();
    }catch (Exception e){

Note: the clone method implements the shallow copy (to generate a new object, the value of the basic type field in the object is the same as that of the source object, and the reference field is the same as the address pointed to by the source object). If you want to realize the deep copy, you need to rewrite the clone method to realize the deep traversal copy of the domain object.

Article 11 of effective Java, Article 20 of Ali programming specification - > programming specification - > OOP specification


6. Grammar sugar: automatic packing and unpacking

The compiler will automatically pack or unpack the basic types and their wrapper classes

  • Perform = assignment (packing or unpacking)
  • Perform +, -, *, / mixed operation (unpacking)
  • Carry out the comparison operation (unpacking)
  • Call equals for comparison (boxing)
  • When adding basic type data to collection classes such as ArrayList and HashMap (boxing)
static void autoBox(){
    // unbox is equivalent to int a= new Integer(200).intValue();
    int a = new Integer(200);
    // box is equivalent to integer B= Integer.valueOf (200);
    Integer b = 200;
    //auto unbox
    // unbox
    // unbox
    // box

    //box note: Integer.valueOf Method in the range of - 127 to 127 returns the integer object taken from the cache,
    // Out of this range, new objects are returned.
    Integer aa =100;
    Integer bb =100;
    Integer aa1 =200;
    Integer bb1 =200;




Tags: Java Programming jvm

Posted on Sun, 28 Jun 2020 00:21:02 -0400 by jswinkelman