Common Java classes: Object class

Posted by afam4eva on Mon, 07 Mar 2022 20:49:25 +0100

Common Java classes: Object class

summary

  • It is a super class and base class, which is located at the top of the inheritance number. It is the direct or indirect parent of all classes
  • As long as any class does not declare extends to inherit a class, it will inherit the Object class by default. Otherwise, it will inherit the Object class indirectly
  • The methods defined in the Object class are the methods of all objects, so subclasses can use all methods of Object

All methods:

Modifiers and typesMethod and description
protected Objectclone() creates and returns a copy of this object.
booleanequals(Object obj) indicates whether some other object is equal to this.
protected voidfinalize() when the garbage collector determines that there is no longer a reference to the object, the garbage collector calls the object on the object.
Class<?>getClass() returns the runtime class of this Object.
inthashCode() returns the hash code value of the object.
voidnotify() wakes up a single thread waiting for the object monitor.
voidnotifyAll() wakes up all threads waiting for the object monitor.
StringtoString() returns the string representation of the object.
voidwait() causes the current thread to wait until another thread calls the notify() method or notifyAll() method of the object.
voidwait(long timeout) causes the current thread to wait until another thread calls the notify() method or the notifyAll() method of the object, or the specified time has passed.
voidwait(long timeout, int nanos) causes the current thread to wait until another thread calls the notify() method or notifyAll() method of the object, or some other thread interrupts the current thread, or a certain amount of real-time time time.

Demonstration class:

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

getClass() method

  • Type: class <? >

  • Returns the actual object type stored in the reference

  • Function: it is usually used to judge whether the actual storage object types in two references are consistent

  • Example:

    public class TestStudent {
        public static void main(String[] args) {
    
            Student s1 = new Student("lisa",20);
            Student s2 = new Student("kirot", 21);
    
            //Judge whether s1 and s2 are of the same type: getClass();
            Class class1 = s1.getClass();
            Class class2 = s2.getClass();
    
            System.out.println(class1 == class2 ? "s1 and s2 Belong to the same type" : "s1 and s2 Not of the same type");
    
        }
    }
    

    output

    s1 and s2 Belong to the same type
    

hashCode() method

  • Type: int

  • Returns the hash code value of the object

  • Hash value a numeric value of type int calculated using the hash algorithm based on the address or string or number of the object

  • Generally, the same object returns the same hash code value

  • Example:

    public class TestStudent {
        public static void main(String[] args) {
    
            Student s1 = new Student("lisa",20);
            Student s2 = new Student("kirot", 21);
    
            //Returns the hash code values of s1 and s2. The hash codes returned by different objects are different
            System.out.println(s1.hashCode());
            System.out.println(s2.hashCode());
    
            Student s3 = s1;
            //s1 address is assigned to s3, so their hash code values are the same
            System.out.println(s3.hashCode());
    
        }
    }
    

    output

    2129789493
    668386784
    2129789493
    

toString() method

  • Type: String

  • Returns the string representation of the object

  • Example:

    public class TestStudent {
        public static void main(String[] args) {
    
            Student s1 = new Student("lisa",20);
            Student s2 = new Student("kirot", 21);
    
            //Returns the string representation of the object: class name + @ + hexadecimal hash code value
            System.out.println(s1.toString());
            System.out.println(s2.toString());
    
        }
    }
    

    output

    Student@7ef20235
    Student@27d6c5e0
    
  • Extension: you can also override the toString() method in the class to return your own custom string

  • Example:

    Override Student class

    public class Student {
        private String name;
        private int age;
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
    public class TestStudent {
        public static void main(String[] args) {
    
            Student s1 = new Student("lisa",20);
            Student s2 = new Student("kirot", 21);
    
            //Returns the string representation of the object
            System.out.println(s1.toString());
            System.out.println(s2.toString());
    
        }
    }
    

    output

    Student{name='lisa', age=20}
    Student{name='kirot', age=21}
    

equals() method

  • Type: boolean

  • The default implementation is (this == obj). Compare whether the addresses of two objects are the same

  • You can overwrite and compare whether the contents of the two objects are the same

  • Example:

    public class TestStudent {
        public static void main(String[] args) {
    
            Student s1 = new Student("lisa",20);
            Student s2 = new Student("kirot", 21);
    
            //equals(); Judge whether two objects are equal
            System.out.println(s1.equals(s2));
    
            Student s3 = s1;    //s1 address assigned to s3
            System.out.println(s1.equals(s3));
    
            Student s4 = new Student("w",18);
            Student s5 = new Student("w",18);
            System.out.println(s4.equals(s5)); //The addresses of s4 and s5 are different
    
        }
    }
    

    output

    false
    true
    false
    

Override steps for the equals() method

  • Compare whether two references point to the same object

  • Judge whether obj is null

  • Judge whether the actual object types pointed to by the two references are consistent

  • Cast type

  • Compare whether the attribute values are the same in turn

  • Examples

    Override the equals() method

    public class Student {
        private String name;
        private int age;
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public boolean equals(Object obj) {
            //1. Judge whether two objects are the same reference
            if (this == obj) {
                return true;
            }
            //2. Judge whether obj is null
            if (obj == null) {
                return false;
            }
            //3. Judge whether it is the same type
            if (obj instanceof Student) {   //instanceof determines whether an object is of a certain type
                //4. Cast type
                Student s = (Student) obj;
                //5. Compare attributes
                if (this.name.equals(s.getName()) && this.age == s.getAge()) {
                    return true;
                }
            }
            return false;
        }
    }
    
    public static void main(String[] args) {
    
            Student s1 = new Student("lisa",20);
            Student s2 = new Student("kirot", 21);
    
            //equals(); Judge whether two objects are equal
            System.out.println(s1.equals(s2));
    
            Student s3 = s1;    //s1 address assigned to s3
            System.out.println(s1.equals(s3));
    
            Student s4 = new Student("w",18);
            Student s5 = new Student("w",18);
            System.out.println(s4.equals(s5));
    
        }
    

    output

    false
    true
    true
    

finalize() method (deprecated)

  • When the object is determined to be a garbage object, the JVM will automatically call this method to mark the garbage object and enter the collection queue
  • Garbage object: garbage object when there is no valid reference to this object
  • Garbage collection: GC destroys garbage objects to free up data storage space
  • Automatic recycling mechanism: the JVM runs out of memory and recycles all garbage objects at one time
  • Manual recycling mechanism: use system gc(); Notify the JVM to perform garbage collection

clone() method

  • Create and return a copy of this object

  • clone() is a shallow copy. The object referenced by the attribute in the object will only copy the reference address without reallocating the memory of the referenced object. The corresponding deep copy will recreate the referenced object

  • Because the Object itself does not implement the clonable interface, CloneNotSupportedException will occur if the clone method is not rewritten and called

  • Example:

    public class Student implements Cloneable{
        private String name;
        private int age;
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
        
        public static void main(String[] args) {
    
            Student s1 = new Student("dt", 20);
            System.out.println(s1.getName()+"\t"+s1.getAge());
    
            try {
                //Create a copy of s1
                Student s2 = (Student) s1.clone();
                System.out.println(s2.getName()+"\t"+s2.getAge());
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
    
        }
    
    }
    

    output

    dt	20
    dt	20
    

Topics: Java