WHAT IS instanceof KEYWORD ?

instanceof is a keyword in java.
It returns true/false.
When a class(Dog) is a sub-class of any other class(Animal) then it returns true.
class Animal{}
class Dog extends Animal{}
class Demo{
public static void main(String[] args){
Dog dog=new Dog();
Animal animal=new Animal();
System.out.println(dog instancof Animal);//it prints true
System.out.println(animal instanceof Dog);//it prints false
}}
This is because Dog is subclass of Animal.
Every calss is a sub-class of Object
so
dog instancof Object //returns true
animal instanceof Object//returns true

Test whether the null reference is an instance of a class.This will always result in false,
e.g.
class InstanceTest {
public static void main(String [] args) {
String a = null;
boolean b = null instanceof String;
boolean c = a instanceof String;
System.out.println(b + " " + c);
}
}
prints this: false false

Remember that arrays are objects, even if the array is an array of
primitives. Watch for questions that look something like this:
int [] nums = new int[3];
if (nums instanceof Object) { } // result is true

An array is always an instance of Object. Any array.

CHECK THIS
interface Foo { }
class A implements Foo { }
class B extends A { }
...
A a = new A();
B b = new B();
the following are true:
a instanceof Foo
b instanceof A
b instanceof Foo // implemented indirectly

No comments:

Post a Comment