The Object class is the ultimate ancestor—every class in Java extends Object. However, you never have to write class Employee extends Object
The ultimate superclass Object is taken for granted if no superclass is explicitly mentioned. Because every class in Java extends Object, it is important to be familiar with the services provided by the Object class. We go over the basic ones in this chapter and refer you to later chapters or to the on-line documentation for what is not covered here. (Several methods of Object come up only when dealing with threads —see Volume II for more on threads.)
You can use a variable of type Object to refer to objects of any type:
Of course, a variable of type Object is only useful as a generic holder for arbitrary values. To do anything specific with the value, you need to have some knowledge about the original type and then apply a cast:
In Java, only the primitive types (numbers, characters, and boolean values) are not objects.
All array types, no matter whether they are arrays of objects or arrays of primitive types, are class types that extend the Object class.
C++ NOTE:In C++, there is no cosmic root class. However, every pointer can be converted to a void* pointer.
The equals Method
The equals method in the Object class tests whether one object is considered equal to another.
The equals method, as implemented in the Object class, determines whether two object references are identical. This is a pretty reasonable default —if two objects are identical, they should certainly be equal. For quite a few classes, nothing else is required. For example, it makes little sense to compare two PrintStream objects for equality. However, you will often want to implement state-based equality testing, in which two objects are considered equal when they have the same state.
For example, let us consider two employees equal if they have the same name, salary, and hire date. (In an actual employee database, it would be more sensible to compareIDs instead. We use this example to demonstrate the mechanics of implementing theequals method.)
The getClass method returns the class of an object—we discuss this method in detail later in this section. In our test, two objects can only be equal when they belong to the same class.
When you define the equals method for a subclass, first call equals on the superclass. If that test doesn’t pass, then the objects can’t be equal. If the superclass fields are equal, then you are ready to compare the instance fields of the subclass.
Equality Testing and Inheritance
How should the equals method behave if the implicit and explicit parameters don’t belong to the same class? This has been an area of some controversy. In the preceding example, the equals method returns false if the classes don’t match exactly. But many programmers
use an instanceof test instead:
This leaves open the possibility that otherObject can belong to a subclass. However, this approach can get you into trouble. Here is why. The Java Language Specification requires that the equals method has the following properties:
These rules are certainly reasonable. You wouldn’t want a library implementor to ponderwhether to call x .equals(y) or y.equals(x) when locating an element in a data structure.
However, the symmetry rule has subtle consequences when the parameters belong to different classes. Consider a call e.equals(m) where e is an Employee object and m is a Manager object, both of which happen to have the same name, salary, and hire date. If Employee.equals uses an instanceof test, the call returns true. But that means that the reverse call m.equals(e) also needs to return true—the symmetry rule does not allow it to return false or to throw an exception.
That leaves the Manager class in a bind. Its equals method must be willing to compare itself to any Employee, without taking manager -specific information into account! All of a sudden, the instanceof test looks less attractive!
Some authors have gone on record that the getClass test is wrong because it violates the substitution principle. A commonly cited example is the equals method in the AbstractSet class that tests whether two sets have the same elements. The AbstractSet class has two concrete subclasses, TreeSet and HashSet, that use different algorithms for locating set elements. You really want to be able to compare any two sets, no matter how they are implemented.
However, the set example is rather specialized. It would make sense to declare Abstract -Set.equals as final, because nobody should redefine the semantics of set equality. (The method is not actually final. This allows a subclass to implement a more efficient algorithm for the equality test.)
The way we see it, there are two distinct scenarios:
In the example of the employees and managers, we consider two objects to be equal when they have matching fields. If we have two Manager objects with the same name, salary, and hire date, but with different bonuses, we want them to be different. Therefore, we used the getClass test.
But suppose we used an employee ID for equality testing. This notion of equality makes sense for all subclasses. Then we could use the instanceof test, and we should declare Employee.equals as final.
NOTE: The standard Java library contains over 150 implementations of equals methods, with a mishmash of using instanceof, calling getClass, catching a ClassCastException, or doing nothing at all.
Here is a recipe for writing the perfect equals method:
This statement is just an optimization. In practice, this is a common case. It is much cheaper to check for identity than to compare the fields.
If the same semantics holds for all subclasses, you can use an instanceof test:
If you redefine equals in a subclass, include a call to super.equals(other).
TIP: If you have fields of array type, you can use the static Arrays.equals method to check that corresponding array elements are equal.
CAUTION: Here is a common mistake when implementing the equals method. Can you spotthe problem?
This method declares the explicit parameter type as Employee. As a result, it does not override the equals method of the Object class but defines a completely unrelated method.
Starting with Java SE 5.0, you can protect yourself against this type of error by tagging methods that are intended to override superclass methods with @Override:@Override public boolean equals(Object other)
If you made a mistake and you are defining a new method, the compiler reports an error. For example, suppose you add the following declaration to the Employee class:@Override public boolean equals(Employee other)
An error is reported because this method doesn’t override any method from the Object superclass.
positions. The arrays can have component types Object, int, long, short, char, byte, boolean, float, or double.
The hashCode Method
A hash code is an integer that is derived from an object. Hash codes should be scrambled— if x and y are two distinct objects, there should be a high probability that x.hash- Code() and y.hashCode() are different. Table below lists a few examples of hash codes that result from the hashCode method of the String class.
The String class uses the following algorithm to compute the hash code:
Hash Codes Resulting from the hashCode Function
The hashCode method is defined in the Object class. Therefore, every object has a defaulthash code. That hash code is derived from the object’s memory address. Consider this example:
Table below shows the result
Hash Codes of Strings and String Builders
Note that the strings s and t have the same hash code because, for strings, the hash codes are derived from their contents. The string builders sb and tb have different hash codes because no hashCode method has been defined for the StringBuilder class, and the default hashCode method in the Object class derives the hash code from the object’s memory address.
If you redefine the equals method, you will also need to redefine the hashCode method for objects that users might insert into a hash table.
The hashCode method should return an integer (which can be negative). Just combine thehash codes of the instance fields so that the hash codes for different objects are likely tobe widely scattered.
For example, here is a hash Code method for the Employee class:
Your definitions of equals and hashCode must be compatible: if x.equals(y) is true, then x.hashCode() must be the same value as y.hashCode(). For example, if you define Employee.equals to compare employee IDs, then the hashCode method needs to hash the IDs, not employee names or memory addresses.
TIP: If you have fields of array type, you can use the static Arrays.hashCode method to compute a hash code that is composed of the hash codes of the array elements.
The toString Method
Another important method in Object is the toString method that returns a string representing the value of this object. Here is a typical example. The toString method of the Point class returns a string like this:
Most (but not all) toString methods follow this format: the name of the class, followed by the field values enclosed in square brackets. Here is an implementation of the toString method for the Employee class:
Actually, you can do a little better. Rather than hardwiring the class name into the
toString method, call getClass().getName() to obtain a string with the class name.
The toString method then also works for subclasses.
Of course, the subclass programmer should define its own toString method and add the subclass fields. If the superclass uses getClass().getName(), then the subclass can simply call super.toString(). For example, here is a toString method for the Manager class:
The toString method is ubiquitous for an important reason: whenever an object is concatenated with a string by the “+” operator, the Java compiler automatically invokes the toString method to obtain a string representation of the object. For example:
TIP: Instead of writing x.toString(), you can write "" + x. This statement concatenates the empty string with the string representation of x that is exactly x.toString(). Unlike toString, this statement even works if x is of primitive type.If x is any object and you call
then the println method simply calls x.toString() and prints the resulting string. The Object class defines the toString method to print the class name and the hash code of the object. For example, the callproduces an output that looks like this: java.io.PrintStream@2f6684
The reason is that the implementor of the PrintStream class didn’t bother to override the toString method.
CAUTION: Annoyingly, arrays inherit the toString method from Object, with the added twist that the array type is printed in an archaic format. For example,
yields the string "[I@1a46e30". (The prefix [I denotes an array of integers.) The remedy is to call the static Arrays.toString method instead. The codeyields the string "[2, 3, 5, 7, 11, 13]".
To correctly print multi dimensional arrays (that is, arrays of arrays), use Arrays .deep To String. The toString method is a great tool for logging. Many classes in the standard class library
define the toString method so that you can get useful information about the state of an object. This is particularly useful in logging messages like this:As we explain , an even better solution is
TIP: We strongly recommend that you add a toString method to each class that you write. You, as well as other programmers who use your classes, will be grateful for the logging support.
NOTE: Cloning an object is important, but it also turns out to be a fairly subtle process filled with potential pitfalls for the unwary.
Core Java Related Interview Questions
|J2EE Interview Questions||Core Java Interview Questions|
|JDBC Interview Questions||JSP Interview Questions|
|Android Interview Questions||JavaServer Faces (JSF) Interview Questions|
|Java collections framework Interview Questions||Java 8 Interview Questions|
|Java Collections Interview Questions||Java Exception Handling Interview Questions|
|Java Concurrency Interview Questions||Java Serialization Interview Questions|
|Java Programmer Interview Questions||Java Inheritance Interview Questions|
|Java IO Interview Questions||Object Oriented Programming in PHP Interview Questions|
Core Java Tutorial
An Introduction To Java
The Java Programming Environment
Fundamental Programming Structures In Java
Objects And Classes
Interfaces And Inner Classes
User Interface Components With Swing
Deploying Applications And Applets
Exceptions, Logging, Assertions, And Debugging
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.