The instanceof is used to knowing the type of an object during run time. The instanceof operator has this general form :

objref instanceof type

Here, objref is a reference to an instance of a class, and type is a class type. If objref is of the specified type or can be cast into the specified type, then the instanceof operator evaluates to true. Otherwise, its result is false. Thus, instanceof is the means by which your program can obtain run-time type information about an object.



Program Source

class DataA {

class DataB extends DataA{


class DataC {


class DataD extends DataC {


public class Javaapp {
    public static void main(String[] args) {
        DataA a = new DataA();
        DataB b = new DataB();
        DataC c = new DataC();
        DataD d = new DataD();
        if(a instanceof DataA)
            System.out.println("a instance of DataA");
        if(b instanceof DataB)
            System.out.println("b instance of DataB");
        if(c instanceof DataC)
            System.out.println("c instance of DataC");
        if(d instanceof DataD)
            System.out.println("d instance of DataD");
        if(b instanceof DataA)
            System.out.println("b extends DataA");
        if(d instanceof DataC)
            System.out.println("d extends DataC");

One thought on “Java-Instanceof

Leave a Comment