Java Reference
In-Depth Information
else {
System.out.println("false");
}
This time, the compiler will refuse to compile the above code. Let's apply the logic and try to figure out what is
wrong with the code. The compiler will generate an error about the
jim instanceof Munificent
expression. It is
saying that it knows for sure that there is no possibility at runtime that the variable
jim
can refer to an object whose
class implements the
Munificent
interface. How can the compiler be so sure about this possibility? It is easy. You have
declared the
StingyGiver
class as
final
, which means it cannot be subclassed. This implies that the variable
jim
whose compile-time type is
StingyGiver
can only refer to an object whose class is
StingyGiver
. The compiler also
knows that the
StingyGiver
class and none of its ancestor classes implement the
Munificent
interface. With all these
reasoning, the compiler determines that you have a logical error in your program and you need to fix it.
If the
instanceof
operator returns
true
at runtime, it means that its left-hand operand can be safely cast to
the type represented by its right-hand operand. Typically, your logic will be as follows when you need to use the
instanceof
operator:
ABC a = null;
DEF d = null;
if (x instanceof ABC) {
// Safe to cast x to ABC type
a = (ABC)x;
}
else if (x instanceof DEF) {
// Safe to cast x to DEF type
d = (DEF)x;
}
If the left-hand operand of the
instanceof
operator is
null
or a reference variable, which points to
null
at
runtime, it returns
false
. The following snippet of code will also print
false
:
Giver ken = null;
if (ken instanceof Munificent) {
System.out.println("true");
}
else {
System.out.println("false");
}
You can conclude that if
v instanceof XYZ
returns
true
, you can assume the following two things safely:
•
v
is not
null
. That is,
v
is pointing to a valid object in memory.
The cast
•
(XYZ)v
will always succeed. That is, the following code is guaranteed to work at
runtime without a
ClassCastException
:
XYZ x = (XYZ)v;
Marker Interfaces
You can declare an interface with no members. Note that an interface can have members in two ways: by declaring
its own members or by inheriting members from its superinterfaces. When an interface has no members (declared
or inherited), it is known as a
marker
interface. A marker interface is also called a
tag
interface. What is the use of a