Chapter 1 Object class
1.1 general
Parent of all classes
If a class does not specify a parent class, it inherits from the Object class by default. For example:
public class MyClass /*extends Object*/ { // ... }
According to the JDK source code and the API documents of the Object class, the Object class contains 11 methods. Today we will mainly learn two of them:
- public String toString(): returns the string representation of the object.
- public boolean equals(Object obj): indicates whether another object is "equal" to this object.
1.2 toString method
- public String toString(): returns the string representation of the object.
The toString method returns the string representation of the object. In fact, the string content is the type + @ + memory address value of the object.
Since the result returned by the toString method is the memory address, it is often necessary to get the corresponding string representation according to the object properties in development, so it also needs to be rewritten.
Overwrite
If you do not want to use the default behavior of the toString method, you can override it. For example, the custom Person class:
public class Person { private String name; private int age; @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } // Omit constructor and Getter Setter }
Insert the code slice here
1.3 equals method
Method summary
- public boolean equals(Object obj): indicates whether another object is "equal" to this object.
- If you call the member method equals and specify another object as the parameter, you can judge whether the two objects are the same. The "same" here has two methods: default and user-defined.
Default address comparison
If the equals method is not overridden, the Object address comparison of the = = operator is performed by default in the Object class. As long as it is not the same Object, the result must be false.
Object content comparison
If you want to compare the contents of objects, that is, if all or some of the specified member variables are the same, you can override the equals method. For example:
import java.util.Objects; public class Person { private String name; private int age; @Override public boolean equals(Object o) { // If the object addresses are the same, they are considered the same if (this == o) return true; // If the parameter is empty or the type information is different, it is considered different if (o == null || getClass() != o.getClass()) return false; // Convert to current type Person person = (Person) o; // The basic types are required to be equal, and the reference type is given to the equals static method of the java.util.Objects class to get the result return age == person.age && Objects.equals(name, person.name); } }
1.4 Objects class
In the automatic rewrite of equals code in IDEA just now, the java.util.Objects class was used. What is this class?
An Objects tool class is added in JDK7. It provides some methods to operate Objects. It consists of some static practical methods. These methods are null save (null pointer safe) or null tolerance (null pointer tolerant), which are used to calculate the hashcode of the object, return the string representation of the object, and compare the two Objects.
When comparing two Objects, the equals method of Object is easy to throw null pointer exceptions, and the equals method in the Objects class optimizes this problem. The method is as follows:
- public static boolean equals(Object a, Object b): judge whether two objects are equal.
Check the source code:
public static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); }
Member method of Object class
public int hashCode()
public final Class getClass()
public String toString()
public boolean equals(Object obj)
protected void finalize()
protected Object clone()
//public int hashCode() //public final Class getClass() //public String toString() public class StudentTest2 { public static void main(String[] args) { Student2 s1 = new Student2(); System.out.println(s1.hashCode());//Print hash value System.out.println(s1.getClass().getName()); //com.shujia.java.day14.Student2 System.out.println("***************************"); System.out.println(s1.toString()); // com.shujia.java.day14.Student2@4554617c System.out.println("***********"); //The toString() method is equivalent to the following: //getClass().getName() + '@' + Integer.toHexString(hashCode()) //this.getClass().getName()+"@"+Integer.toHexString(this.hashCode) // com.shujia.java.day14.Student2@4554617c System.out.println(s1.getClass().getName()+"@"+Integer.toHexString(s1.hashCode())); s1.setName("AAA"); s1.setAge(18); System.out.println(s1.toString()); //To print the object itself, the toString() method is called by default System.out.println(s1); } }
public boolean equals(Object obj)
Student3 class
public class Student3 { private String name; private int age; public Student3() { } public Student3(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 "Student3{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object obj) { //Object obj = new Student3(); // return true; //s1 -- this //s4 -- obj //To access members in the parent class, you need to transition down if (this == obj){ return true; } Student3 s = (Student3)obj; return this.name.equals(s.getName()) && this.age == s.getAge(); } // @Override // public boolean equals(Object obj) { // return super.equals(obj); // } }
Student3 test class
/* public boolean equals(Object obj)Indicates whether some other objects are equal to this. This method compares the address value by default. By observing the source code, it is found that the underlying default call is = = to compare two objects, The = = compares whether the address values are the same, so system. Out. Println (S1. Equals (S2))// false However, comparing address values is meaningless. In more cases, we should compare the member variables in the object Whether the values of are the same. ==: Basic data type: compares whether the values are the same Reference data type: compares whether the address values are the same equals: Because equals is a method in the Object class, only objects can be called, and the basic data type does not belong to objects Reference type: by default, the address value is compared and needs to be rewritten according to the situation, but we don't need to rewrite it ourselves It can be generated automatically, but the implementation logic needs to be written by itself */ public class StudentTest3 { public static void main(String[] args) { Student3 s1 = new Student3("AA", 18); Student3 s2 = new Student3("AA", 18); System.out.println(s1 == s2);//false Student3 s3 = s1; System.out.println(s1 == s3); // true System.out.println("***********************"); System.out.println(s1.equals(s2)); //false System.out.println(s1.equals(s1)); //true System.out.println(s1.equals(s3)); //true Student3 s4 = new Student3("BBB", 18); System.out.println(s1.equals(s4)); } }
protected void finalize()
protected Object clone()
public class Student4 implements Cloneable{ private String name; private int age; public Student4() { } public Student4(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 "Student4{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
/* protected void finalize() throws Throwable When the garbage collection determines that there is no longer a reference to the object, the garbage collector calls the object on the object. In short, it is used for garbage collection. When to recycle is uncertain. protected Object clone() throws CloneNotSupportedException Create and return a copy of this object. What is returned is a clone of this instance, which is received by the Object class clone A new object will be created. Interface Cloneable This must be implemented using the clone method However, by observing the API, we find that the interface does not have any abstract methods, so what is the significance of implementing this interface? If the interface is called directly without rewriting it, an error CloneNotSupportedException will be reported An interface like this without any method is called a tag interface */ public class StudentTest4 { public static void main(String[] args) throws CloneNotSupportedException { Student4 s1 = new Student4(); s1.setName("floret"); s1.setAge(18); System.out.println(s1.toString()); Object s1Clone = s1.clone(); //Downward transformation Student4 sClone = (Student4) s1Clone; System.out.println(s1.getName()+"---"+s1.getAge()); System.out.println(sClone.getName()+"---"+sClone.getAge()); Student4 s2 = s1; //There is always only one object in heap memory System.out.println(s2.getName()+"---"+s2.getAge()); s2.setName("Xiaobai"); s2.setAge(20); System.out.println(s1.getName()+"---"+s1.getAge()); System.out.println(sClone.getName()+"---"+sClone.getAge()); } }