If I try to use instanceof operator with wrong class I'm getting a compile error (" Animal can not be converted to String") but with an interface I'm not getting compile time error.
For eg: In line 10 I'm getting a compile error because Animal is not a subclass of String. But in line 14 I'm not getting a compile error even though Animal does not implement List interface.
class Animal {
}
public class InstanceOf {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Animal a = new Animal();
if (a instanceof String ){ //line 10
System.out.println("True");
}
if (a instanceof List ){ //line 14
System.out.println("True");
}
}
}
instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.
Is a class an Instanceof an interface? If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.
As the name suggests, instanceof in Java is used to check if the specified object is an instance of a class, subclass, or interface.
No interface cannot have instance variable.
a
can never be an instanceof String, hence the compilation error.
a
can be an instance of List
if some sub-class of Animal
would implement the List
interface and you would assign an instance of such sub-class to a
. Therefore the compiler allows it.
From the JLS :
If a cast (§15.16) of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.
Just an experiment I did from this question.
class Animal {}
interface AnimalA {}
class AnimalB{}
class AnimalC extends Animal,AnimalB {} //not possible
class AnimalD extends Animal implements AnimalA{} //possible
public class InstanceOfTest {
public static void main(String[] args) {
Animal a = new Animal();
if(a instanceof AnimalA) { //no compile time error
System.out.println("interface test");
}
if(a instanceof AnimalB) { //compile time error
System.out.println("interface test");
}
if(a instanceof List) { //compile time error
System.out.println("interface test");
}
if(a instanceof ArrayList) { //compile time error
System.out.println("interface test");
}
}
}
So as @Eran said, as Animal
is not a sub-class of AnimalB
non of its sub-class can become and instance of AnimalB
. But on the other any of its sub-class can implement interface
List.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With