Phone Class Properties:
1 Private String Id; 2 Private String name;
After overriding the Equals method:
1 //overriding the Equals method2 @Override3 Public Booleanequals (Object obj) {4 //determine if the same object5 if( This==obj) {6 return true;7 }8 //determine if obj is an instance of the phone9 if(! (objinstanceofPhone)) {Ten return false; One } A //Forced Conversions -Phone phone =(Phone) obj; - //determine whether each property is equal in turn the if(!getId (). Equals (Phone.getid ())) { - return false; - } - if(!getName (). Equals (Phone.getname ())) { + return false; - } + return true; A}
Test:
1 New Phone ("1234", "IPH"); 2 Phone phone2=New phone ("1234", "IPH"); 3 System.out.println (Phone.equals (phone2));
Output Result:
True
All Class Code:
1 Public classPhone {2 PrivateString Id;3 PrivateString name;4 5 PublicPhone () {6 }7 8 PublicPhone (String Id, string name) {9 This. Id =Id;Ten This. Name =name; One } A - PublicString getId () { - returnId; the } - - Public voidsetId (String id) { -Id =ID; + } - + PublicString GetName () { A returnname; at } - - Public voidsetName (String name) { - This. Name =name; - } - in //overriding the Equals method - @Override to Public Booleanequals (Object obj) { + //determine if the same object - if( This==obj) { the return true; * } $ //determine if obj is an instance of the phonePanax Notoginseng if(! (objinstanceofPhone)) { - return false; the } + //Forced Conversions APhone phone =(Phone) obj; the //determine whether each property is equal in turn + if(!getId (). Equals (Phone.getid ())) { - return false; $ } $ if(!getName (). Equals (Phone.getname ())) { - return false; - } the return true; - }Wuyi}
Overriding the Equals method