I learned that Java has the instanceof
operator. Can you elaborate where it is used and what are its advantages?
This question is related to
java
operators
instanceof
instanceof
is used to check 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.
instanceof
can be used to determine the actual type of an object:
class A { }
class C extends A { }
class D extends A { }
public static void testInstance(){
A c = new C();
A d = new D();
Assert.assertTrue(c instanceof A && d instanceof A);
Assert.assertTrue(c instanceof C && d instanceof D);
Assert.assertFalse(c instanceof D);
Assert.assertFalse(d instanceof C);
}
instanceof is a keyword that can be used to test if an object is of a specified type.
Example :
public class MainClass {
public static void main(String[] a) {
String s = "Hello";
int i = 0;
String g;
if (s instanceof java.lang.String) {
// This is going to be printed
System.out.println("s is a String");
}
if (i instanceof Integer) {
// This is going to be printed as autoboxing will happen (int -> Integer)
System.out.println("i is an Integer");
}
if (g instanceof java.lang.String) {
// This case is not going to happen because g is not initialized and
// therefore is null and instanceof returns false for null.
System.out.println("g is a String");
}
}
Here is my source.
Source: Stackoverflow.com