Java/J2EE and SOA (304 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (45 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (303 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

How To Implement InstanceOf In JAVA?

Published on Aug 01,2019 88 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

InstanceOf  In Java is an operator, which is used to check the type of an object. In other terms, it tests whether the object is an instance of a specific class or an interface. The output of such an operation is either True or False

Following pointers will be covered in this article,

Moving on with this article on instanceOf in Java.

This operator is also known as type comparison operator, as the instance is compared with the type.

Syntax:

(object) instanceof (type)

An example of the instanceOf operator can be seen below:

public class Main 
{  
public static void main(String[] args) 
{  
Main s = new Main();  
System.out.println(s instanceof Main); 
}  
}

Output

true

In the example, the output returned to the user is true, i.e. “s” is an instance of class Main.

Example

An object of type subclass is also a type of parent class.

In the following example, Rock extends Music. The object of Rock can be referred either by Rock or Music class.

class Music{}
class Rock extends Music
{
//Rock inherits Music
public static void main(String args[])
{
Rock r=new Rock();
System.out.println(r instanceof Rock);
}
}

Output

true

Moving on with this article on instanceOf in Java.

Using a variable with null value

class Music
{
public static void main(String args[])
{
Music m=null;
System.out.println(m instanceof Music);//false
}
}

In the example given above, the variable defined has a null value.

Thus, the output returned is false.

Output

false

The following point must be noted while using the instanceOf operator:

Moving on with this article on instanceOf in Java.

A parent object is not an instance of Child

class Parent {  } 
class Child extends Parent { } 
class Main
{ 
public static void main(String[] args) 
{ 
Parent p = new Parent(); 
if(p instanceof Child) 
System.out.println("p is an instance of Child"); 
else
System.out.println("p is not an instance of Child"); 
} 
}

Output

P is not an instance of Child

Moving on with this article on instanceOf in Java.

Downcasting

When an object of Parent class is referred to by a Subclass, the method is known as downcasting.

On performing downcasting directly, the compiler returns a compilation error.

Rock r=new Music();//compilation error

On using typecasting, ClassCastException is thrown at the runtime.

Rock r=(Rock)new Music();//compilation successful but ClassCastException thrown

The only method by which downcasting is possible is by using  the instanceof operator.

class Music { }
class Rock extends Music {
static void method(Music m) {
if(m instanceof Rock){
Rock r=(Rock)m; //downcasting
System.out.println("Downcasting Successful");
}
}
public static void main (String [] args) {
Music m=new Rock();
Rock.method(m);
}
} 

Output

Downcasting Successful

Moving on with this article on instanceOf in Java.

Understanding instanceOf:

The instanceOf method can be understood more explicitly by the examples given below:

This example makes usage of an interface:

interface Instance{}
class S implements Instance
{
public void s()
{
System.out.println("First method");
}
}
class T implements Instance
{
public void t()
{
System.out.println("Second method");
}
}
class Invoke
{
void invoke(Instance i)
{ //upcasting
if(i instanceof S)
{
S s=(S)i; //Downcasting 
s.s();
}
if(i instanceof T)
{
T t=(T)i; //Downcasting 
t.t();
}
}
} 
class Main
{
public static void main(String args[])
{
Instance i=new T();
Invoke v=new Invoke();
v.invoke(i);
}
}

The output of the example is as follows:
Second Method

This example demonstrates this concept in a precise manner. Here, the parent class is Instrument, and the two child classes are Guitar and Piano:

class Instrument{}
class Guitar extends Instrument{}
class Piano extends Instrument{}
class Main
{
public static void main(String[] args)
{
Instrument i =new Instrument();
Guitar g = new Guitar();
Piano p = new Piano();
System.out.println(g  instanceof Instrument);		
System.out.println(p  instanceof Instrument);		
System.out.println(i instanceof Guitar);		
System.out.println(i  instanceof Piano);		
i = g;
System.out.println(i instanceof Guitar);		
System.out.println(i instanceof Piano);		
i = p;
System.out.println(i instanceof Guitar);		
System.out.println(i instanceof Piano);		
}
} 

The output is as follows:

true

true

false

false

true

false

false

true

This is how the type of an object is found efficiently. The instanceOf operator proves to be quite useful, given that the methods are executed appropriately.

Thus we have come to an end of this article on ‘instanceOf in Java’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.