instanceof operator in Java

instanceof operator in java can be used to find whether an object is an instance of a particular class or not. This is handy when you pass and object as an instance of Object in a method argument and later inside your method code you may check what class is the passed argument an instance of and accordingly cast the generic Object instance to a specific object.

package com.bharat.instanceofdemo;

package com.bharat.test;

public class InstanceOfOperatorDemo
{

  public static void main(String[] args){

    InstanceOfOperatorDemo t = new InstanceOfOperatorDemo();
    t.testMethod(new One());
    t.testMethod(new Two());
  }

  public void testMethod(Object obj){
    if( obj instanceof One)
    {
      System.out.println("You passed one");
    }
    if(obj instanceof Two)
    {
      System.out.println("You passed Two");
    }
  }

}

class One{
  public String a ="class one";
}

class Two{
  public String b = "Class two";
}

Output

You passed one
You passed Two
Advertisements

, , , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: