Java Reference
In-Depth Information
instanceof
and
getClass()
★
Both the
instanceof
operator and the
getClass()
method can be used to check
the class of an object. The
instanceof
operator simply tests an object for type. The
getClass()
method, used in a test with
==
or
!=
, tests if two objects were created with
the same class. The details follow.
THE
instanceof
OPERATOR
The
instanceof
operator checks if an object is of the type given as its second argument.
The syntax is
Object
instanceof
Class_Name
which returns
true
if
Object
is of type
Class_Name
; otherwise it returns
false
. So, the
following will return
true
if
otherObject
is of type
Employee
:
(otherObject
instanceof
Employee)
Note that this means it returns
true
if
otherObject
is of the type of any descendent
class of
Employee
, because in that case
otherObject
is also of type
Employee
.
THE
getClass()
METHOD
Every object inherits the method
getClass()
from the class
Object
. The method
getClass()
is marked
final
in the class
Object
, so it cannot be overridden. For any
object
of any class,
object.getClass()
returns a representation of the class that was used with
new
to create
object
. Any two
such representations can be compared with
==
or
!=
to determine whether or not they
represent the same class. Thus,
if
(object1.getClass() == object2.getClass())
System.out.println("Same class.");
else
System.out.println("Not the same class.");
will output
Same class
if
object1
and
object2
were created with the same class when
they were created using
new
, and output
Not same class
otherwise.
(continued)