Reputation: 275
class A {}
class B {}
public class Demo {
public static void main(String[] args) {
A a = new A();
System.out.println(a instanceof B);
}
}
This code is giving compile time error.
How can I use instanceof
to give false instead of compile time error when object is not an instance of class specified.
Upvotes: 1
Views: 2052
Reputation: 140318
Quoting JLS Sec 15.20.2:
If a cast (§15.16) of the
RelationalExpression
to theReferenceType
would be rejected as a compile-time error, then theinstanceof
relational expression likewise produces a compile-time error. In such a situation, the result of theinstanceof
expression could never be true.
(Where they are describing RelationalExpression instanceof ReferenceType
)
You can't write B b = (B) a;
either, because A
and B
are both classes (*), and are unrelated, in the sense that A
does not directly or indirectly extend B
, nor vice versa.
As such, a reference to an A
can never contain an instance of a B
, so it is nonsensical to test this. As such, the compiler stops you from testing this, as it likely indicates a logical error.
(*) You could write a instanceof B
if B
were an interface, because a
might refer to a subclass of A
which additionally implements B
, e.g.
class ChildOfA extends A implements B {}
A a = new ChildOfA();
System.out.println(a instanceof B); // fine.
Upvotes: 0
Reputation: 22422
If class A
and B
are not related through inheritance, then compiler will throw an error when you try to perform a instanceof B
In your case, A
is NOT a subclass of B
, so you can't do an instanceof
check like a instanceof B
But, if you change your classes like below:
class A {}
class B extends A {}
public static void main(String[] args) {
B b=new B();
System.out.println(b instanceof A);
}
Now b instanceof A
will return true
because B
IS-A (type of) A
You can read the Java doc here on the same subject:
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
Upvotes: 2
Reputation: 3749
You can use this :
System.out.println(a.getClass().equals(B.class));
Instead of :
System.out.println(a instanceof B);
Upvotes: 1
Reputation: 1140
Java knows an A
cannot be a B
so it won't compile. If you change the line to
Object a = new A();
it will compile (and return false) as it can no longer tell if an Object
can be cast into type B
.
Upvotes: 4