Example instanceof operator

class A{
	public void disp()	{
		System.out.println("it is in A");
	}
}
class B extends A{
	public void disp()	{
		System.out.println("it is in B");
	}
}
class C extends A{
	public void disp()	{
		System.out.println("it is in C");
	}
}
class D extends A{
	public void disp()	{
		System.out.println("it is in D");
	}
}
public class InstanceofDemo1 
{
public void disp(Object o)
{
	if(o instanceof A)
	{
		A a=(A)o;
		a.disp();
		System.out.println("A is true");
	}
	else if(o instanceof B)
	{
		B b=(B)o;
		b.disp();
		System.out.println("B is true");
	}
	else if(o instanceof C)
	{
		C c=(C)o;
		c.disp();
		System.out.println("C is true");
	}
	else if(o instanceof D)
	{
		D d=(D)o;
		d.disp();
		System.out.println("D is true");
	}
	else {
		System.out.println("Not valid object");
	}
}
	public static void main(String[] args) 
	{
		
		InstanceofDemo1 obj=new InstanceofDemo1();
		obj.disp(new A());
		obj.disp(new B());
		obj.disp(new C());
		obj.disp(new D());
	}
}

Download

Operators in Java

Example - equals method
Example - instance of operator


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code