Package cn.itcast_03;
/* Public boolean equals (Object obj): Indicates whether another object is "equal" to this object. * This method, by default, compares the address value. Comparing address values is generally not very meaningful, so we'll rewrite this method. * How to rewrite it? *are generally used to compare the values of the member variables of an object.
* Rewrite the code optimization: improve efficiency, improve the robustness of the program. * Final version: *In fact, it is automatically generated.
(The first is the problem with the downward transition, the demo turns into student), so when you go down, you decide whether it is an object of the class. )
* * See source code: *public boolean equals (Object obj) {*THIS-S1 *OBJ-S2 *return (this = = obj); *} * * ==: *Basic type: The comparison is the same value *Reference type: The comparison is whether the address value is the same(string is a reference type, do not use = =)* Equals: *Reference type: By default, the address value is compared. *However, we can rewrite the method as appropriate. General overrides are automatically generated, comparing the value of the member variable of the object to the same */public class Studentdemo {public static void Main (string[] args) {Student S1 = new Student ("Brigitte", 27);Student s2 = new Student ("Brigitte", 27);System.out.println (S1 = = s2); FalseStudent s3 = S1;System.out.println (S1 = = s3);//TrueSystem.out.println ("---------------");
System.out.println (s1.equals (S2)); obj = s2; FalseSystem.out.println (S1.equals (S1)); TrueSystem.out.println (S1.equals (S3)); TrueStudent S4 = new Student ("Wind Qingyang", 30);System.out.println (S1.equals (S4)); FalseDemo d = new demo ();System.out.println (S1.equals (d)); ClassCastException
}}
Class Demo {}
From for notes (Wiz)
11.28_ Common Objects (the Equals () method of the object class). avi