java common class -- Object class

1.API overview and Object class overview

  • A:API(Application Programming Interface)
    Application programming interface
  • B:Java API
    The classes provided by Java to us encapsulate the underlying implementation,
    We don't need to care about how these classes are implemented, we just need to learn how to use them.
  • C: Overview of object class
    Root class of class hierarchy
    All classes inherit directly or indirectly from this class
  • D: Construction method
    public Object()
    Think back to why in object-oriented:
    By default, the construction method of the subclass accesses the nonparametric construction method of the parent class

2. hashCode() method of object class

public int hashCode()
a: Returns the hash code value of the object. By default, this method is calculated based on the address of the object.
b: In general, hashCode() will not be the same for different objects.
However, the hashCode() value of the same object must be the same.
c: It is not the actual address value of the object, which can be understood as the logical address value.

public class MyTest {
    public static void main(String[] args) {
       // java.lang is a class under this package. You can use no package import
       // Class Object is the root class of class hierarchy. Each class uses Object as its superclass. All objects (including arrays) implement methods of this class.
        //Object is a top-level parent class. All classes inherit directly or indirectly from it
       // Empty parameter construction Object()
        Object obj= new Object();
        //          Returns the hash code value of the object.
        int code = obj.hashCode();
        int code2 = obj.hashCode();
        System.out.println(code);
        System.out.println(code2);

        Object obj2 = new Object();
        int hashCode = obj2.hashCode();
        System.out.println(hashCode);

        //Hash code values of different objects are different

    }
}

3. getClass() method of object class

public final Class getClass()
a: Returns the runtime class of this Object.
b: You can obtain the full name of the object's real Class through a method in the Class.

public class MyTest2 {
    public static void main(String[] args) {
        //  Class <? > getclass() returns the runtime class of this Object.
        // Everything is an object. Class (bytecode file) -- > this file is loaded into memory -- > the JVM will treat the bytecode file of this class as an object
        //We need to create an object for Object.class. This object is called bytecode file Object.class represents bytecode type
        Object obj = new Object();  //Object. Class ---- bytecode object
        Object obj2 = new Object();  //Object. Class ---- bytecode object
        System.out.println(obj);
        System.out.println(obj2);
        System.out.println(obj == obj2);

        //Get bytecode file object. Class ----- > JVM
        Class aClass = obj.getClass();

        Class aClass1 = obj2.getClass();

        System.out.println(aClass == aClass1);// true
    }
}

4. toString() method of object class

  • public String toString()
    • a: Returns the string representation of the object.
      Source code:
      public String toString() {
      return getClass().getName() + "@" + Integer.toHexString(hashCode());
      }
    • b: Its value is equal to:
      getClass().getName() + '@' + Integer.toHexString(hashCode())
    • c: Since data by default is meaningless to us, it is generally recommended to override this method.
      How to rewrite? Generally, all the member variables of this class can be returned
  • B: final version
    Automatic generation
  • C: Directly output the corresponding name, that is, the toString() method of the calling object
public class MyTest3 {
    public static void main(String[] args) {
       // String toString() returns the string table representation of the object.
        Object obj = new Object();
        String name=obj.toString();
        System.out.println(name);
        System.out.println(obj);

        Student student = new Student();
        student.setName("Zhang San");
        student.setAge(23);

        System.out.println(student.toString());//
//If you print an object in the future and the output is not the address value, it means that the toString() method is renewed
        Scanner scanner = new Scanner(System.in);
       // System.out.println(scanner.toString());//

    }
}


class Student extends Object{
    private String name;
    private int 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 +
                '}';
    }
}

5. equals() method of object class

  • Case demonstration
    • a: Indicates whether another object is "equal" to this object.
      Source code:
      public boolean equals(Object obj) {
      return (this == obj);
      }
    • b: By default, objects are compared for the same reference.
    • c: Since the reference of the comparison object is meaningless, it is generally recommended to override this method. Generally used to compare whether the values of member variables are equal
    • d: The difference between = = and equals():

"equals"
Basic data type: no equal method;
Reference data type: because of String, the eight basic data types equals compare the content; if other reference data types do not overwrite the equals method, then judge whether they point to the same reference.
"=="
Basic data type: judge whether the values are equal;
Reference data type: determines whether to point to the same reference.

public class MyTest {
    public static void main(String[] args) {
        Student s1 = new Student("Zhang San", 23);
        Student s2 = new Student("Zhang San", 23);
         System.out.println(s1==s2);
        boolean b = s1.equals(s2);//
        System.out.println(b);

    }
}


class Student {
    private String name;
    private int age;

    public Student() {
    }

    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;
    }


    }

6. Code optimization of equals() method of object class

public class MyTest {
    public static void main(String[] args) {
        Student s1 = new Student("Zhang San", 23);
        Student s2 = new Student("Zhang San", 23);
         System.out.println(s1==s2);
        boolean b = s1.equals(s2);//
        System.out.println(b);

    }
}


class Student {
    private String name;
    private int age;

    public Student() {
    }

    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) {
        // I think the values of the members of the two objects are exactly the same, and they think the two objects are the same.
        //Is the reference he passed in a reference of this class


        //Non empty judgement
        if (obj == null) {
            return false;
        }
        //Considering efficiency
        if (this == obj) {
            return true;
        }

        //From the perspective of robustness
        // Instanceof (explained later) determines whether an object (Reference) is a reference of this type
        if (!(obj instanceof Student)) {
            return false;
        }
        //Downward transformation
        Student stu = (Student) obj;
        //String class is a reference type. You use = = to compare two strings. You compare the address values of two strings. Is it the same
        //If you want to compare the literal contents of two strings, call the equals() method to compare,
        //String extends object {} string also resets the equals() method to compare whether the contents of two strings are the same
        return this.age == stu.age && this.name.equals(stu.name);
    }
}

7. The clone() method of the object class

  • The permission modifier of clone() is protected. When using it, let the class override the method and change the permission modifier of the method to public
    Shallow cloning of objects: shallow cloning and deep cloning
    The clone() method is a shallow clone method

  • Details to note for shallow cloning of objects:

  • 1. If an object needs to call clone, the class of the object must implement the clonable interface.

  • 2. The clonable interface is just an identity interface, without any methods.

  • 3. The shallow cloning of an object is to clone an object. If an object of another class is maintained in the cloned object, then only the address of the other object is cloned instead of the address of the other object
    Another object was cloned.

  • 4. Shallow cloning of objects will not call the constructor.

    Deep cloning of objects (later): IO stream is used to write objects to files with ObjectOutputStream, and then read them back with ObjectInputStream

public class MyTest {
    public static void main(String[] args) throws CloneNotSupportedException {
       // protected Object clone() creates and returns a copy of this object.
        //The clone() method is protected. Do you want the subclass to rewrite some of it, change the modifier of the method to public to rewrite the logic or use the parent class
        Dog dog = new Dog("Prosperous wealth", 3);
        System.out.println(dog.name);
        System.out.println(dog.age);
        
        Dog dog2 = (Dog) dog.clone();
        dog2.name="Xiao Bai";
        System.out.println(dog2.name);
        System.out.println(dog2.age);
        

    }
}


class Dog extends Object implements Cloneable{
    String name;
    int age;

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

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
Published 47 original articles, won praise 1, visited 786
Private letter follow

Tags: Java Programming jvm

Posted on Wed, 29 Jan 2020 04:08:46 -0800 by nikbone