Java Reference
In-Depth Information
mango with an employee? You would say no. The compiler adds checks for this kind of illogical comparison using the
instanceof
operator. It makes sure that it is possible for the left-hand operand of the
instanceof
operator to hold a
reference of an object of the right-hand operand type. If it is not possible, the compiler generates an error. It is easy to
find out whether the compiler will generate an error for using the
instanceof
operator or not. Consider the following
snippet of code:
Manager mgr = null;
if (mgr instanceof Clerk) { // A compile-time error
}
The variable
mgr
can hold a reference of
Manager
type or its descendant type. However, it can never hold a
reference of the
Clerk
type. The
Clerk
type is not in the same inheritance-chain as the
Manager
class, although it is in
the same inheritance tree. For the same reason, the following use of the
instanceof
operator will generate a compiler
error because the
String
class is not in the inheritance-chain of the
Employee
class.
String str = "test";
if (str instanceof Employee) { // A compile-time error
}
■
an object is considered an instance of a class if that object is of that class type, or its direct or indirect
descendant type. You can use the
instanceof
operator to check if an object is an instance of a class or not.
Tip
Sometimes you may end up writing code that uses the
instanceof
operator to test for multiple conditions at one
place, as follows:
Employee emp;
// Some logic goes here...
if (emp instanceof Employee) {
// Code to deal with a employee
}
else if (emp instanceof Manager) {
// Code to deal with a manager
}
else if (emp instanceof Clerk) {
// Code to deal with a clerk
}
You should avoid writing this kind of code. If you add a new subclass of
Employee
, you will need to add the logic
for the new subclass to the above code. Usually, this kind of code indicates a design flaw. Always ask yourself the
question, “Will this code keep working when I add a new class to the existing class hierarchy?” If the answer is yes, you
are fine. Otherwise, reconsider the design.
The
equals()
method is the one place in which you will often end up using the
instanceof
operator. It is defined
in the
Object
class and the method is inherited by all classes. It takes an
Object
argument. It returns
true
if the
argument and the object on which this method is called are considered equal. Otherwise, it returns
false
. Objects
of each class may be compared for equality differently. For example, two employees may be considered equal if they
work for the same company and in the same department and have same employee id. What happens if a
Manager