Class Object
Object class is the parent class of all Java class types (or ancestor class is more suitable)
The first chapter of Thinking in Java is called "everything is Object". Everything is an object.
toString() method: Self Description
Any class inherits Object by default, so there are toString() methods:
public class Test { public static void main(String[] args) { Test a = new Test(); System.out.println(a.toString()); System.out.println(a); } }
When printing an Object, we call the toString() method of this class by default. Even if there is no toString() code in the definition of this class, we will inherit this method from the Object.
The toString() method in the Object class is defined as:
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
The default string is "class name @ hashCode".
hashCode is a calculated value. In some places, it is said that this is the address of the object, which is not rigorous, but it is not a big problem.
You can loosely assume that this string represents the address of the object.
Rewrite toString to realize self description
class Person { public Person(String name) { this.name = name; } private String name; @Override public String toString() { return getClass().getName() + "{" + name + "}"; } } public class TestToString { public static void main(String[] args) { Person a = new Person("Monkey King"); System.out.println(a.toString()); } }
Result:
Person {sunwalker}
Practical application example:
toString() can be generated automatically: right click source Generate toString()
public class Monkey { private int id; private String type; private String name; // Accessor slightly @Override public String toString() { return "Monkey [id=" + id + ", type=" + type + ", name=" + name + "]"; } }
equals method and==
There is no difference between the equals method and the = = operator in the Object class (two Object references are equal to be considered equal):
public boolean equals(Object obj) { return (this == obj); }
The String class overrides the equals method, so content equality is determined to be equal.
See the chapter String for details
When you define a class, you can override the equals method to provide a customized judgment standard.
// For example: two classes with the same name are considered equal public class TestOverwriteEquals { public static void main(String[] args) { Food f1 = new Food("rice"); Food f2 = new Food("rice"); System.out.println("==:" + (f1 == f2)); System.out.println("equals:" + f1.equals(f2)); } } class Food { public Food(String name) { this.name = name; } private String name; @Override public boolean equals(Object obj) { if (obj != null && obj.getClass() == Food.class) { Food f = (Food) obj; if (f.name.equals(this.name)) { return true; } } return false; } }
Operation result
==:false equals:true