1

Object class

If a class does not have a specified parent class, it will inherit Object class

public class Student /* extends Object */ {
 // ...
}

  • learning target

    • toString
    • equals

toString

The toString method actually returns the string representation of the object.
key point
toString = object type + "@" + address hashCode (hash value)
toString Since the result returned by , each object different attribute , so we generally need to rewrite it.

Overwrite

Do not want to use the toString method to get the default behavior, you can override it

类
pubilc class Person{

  @Override
  public String toString(){
  return "嘻嘻硕" + "❤" + Integer.toHexString(hashCode());
 }  

}

实现类
public class Demo03 {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.toString());
   }
}

Output result:
Cao Zaishuo 36d64342


equals

equals: Indicates whether an object is "equal" to the comparison object.
== Compare the values of the two variables themselves, that is, the first addresses of the two objects in memory.

== is the default address comparison / equals is the object content comparison

public class Demo02 {
    public static void main(String[] args) {

       String s1 = "abc";
       String s2 = "abc";


        System.out.println(s1 == s2); // true 因为地址是一样的

        String s3,s4,s5 = "abc";

        s3 = new String("abc");
        s4 = new String("abc");

        System.out.println(s3 == s4);   // false 地址不同 new会开辟一个新的地址
        System.out.println(s3.equals(s4)); // true 结果一致 所以为true


    }
}

Deepen the impact

String s1,s2,s3 = "abc" , s4 = "abc";
        s1 = new String("abc");
        s2 = new String("abc");

        // ==
        System.out.println("s1 == s2: " + (s1 == s2)); 
        System.out.println("s1 == s3: " + (s1 == s3));
        System.out.println("s3 == s4: " + (s3 == s4));

        // equals()
        System.out.println("s1.equals(s2)" + s1.equals(s2));
        System.out.println("s1.equals(s3)" + s1.equals(s3));
        System.out.println("s3.equals(s4)" + s3.equals(s4));

The output is:
s1 == s2: false
s1 == s3: false
s3 == s4: true
s1.equals(s2) : true
s1.equals(s3) : true
s3.equals(s4) : true


Summarize:
== is the comparison address
equals is the comparison object

Take a little more time to learn~


嘻嘻硕
27 声望12 粉丝

想当一只天然呆的鸭qwq