Java Reference
In-Depth Information
// Is otherObject a null reference?
if (otherObject == null) {
return false;
}
// Do they belong to the same class?
if (this.getClass() != otherObject.getClass()) {
return false;
}
// Get the reference of otherObject is a SmartCat variable
SmartCat otherCat = (SmartCat)otherObject;
// Do they have the same names
boolean isSameName = (this.name == null? otherCat.name == null
:this.name.equals(otherCat.name) );
return isSameName;
}
/* Reimplement the hashCode() method, which is a requirement
when you reimplement equals() method */
public int hashCode() {
return (this.name == null? 0 : this.name.hashCode());
}
}
The SmartCat class has a name instance variable, which is of the type String . The String class has its own version
of the equals() method implementation that compares two strings character by character. The equals() method
of the SmartCat class calls the equals() method on the name instance variables to check if two names are equal.
Similarly, it makes use of the hashCode() method's implementation in the String class in its hashCode ( ) method.
String Representation of an Object
An object is represented by its state, which is the combination of values of all its instance variables at a point in time.
Sometimes it is helpful, usually in debugging, to represent an object in a string form. What should be in the string that
represents an object? The string representation of an object should contain enough information about the state of
the object in a readable format. The toString() method of the Object class lets you write your own logic to represent
the object of your class in a string. The Object class provides a default implementation of the toString() method. It
returns a string in the following format:
<<fully qualified class name>>@<<hash code of object in hexadecimal>>
Consider the following snippet of code and its output. You may get a different output.
// Create two objects
Object obj = new Object();
IntHolder intHolder = new IntHolder(234);
// Get string representation of objects
String objStr = obj.toString();
String intHolderStr = intHolder.toString();
 
Search WWH ::




Custom Search