java instanceof keyword

Fri Jan 30, 2009 12:06 am

Java instanceof keyword :
This is an example about java instanceof keyword usage. instanceof keyword is used for avoiding invalid casting classes objects at run time. In brief instanceof operator is used to check if a certain object belongs to a specific class or not. Usually this type of checking is used as a layer of validation at the beginning of general functions to clean the parameters sent to It.

java code
public class Main {

public static void main(String[] args) {

A classA=new A();
B classB=new B();

if(classA instanceof A)
{
System.out.println("Correct");
}
else
System.out.println("Wrong ");
if(classA instanceof Base)
{
System.out.println("Correct");
}
else
System.out.println("Wrong ");

if(classB instanceof A)
{
System.out.println("Correct");
}
else
System.out.println("Wrong ");

if(classB instanceof Base)
{
System.out.println("Correct");
}
else
System.out.println("Wrong ");


}

}
interface Base
{

}
class A implements Base
{
public A()
{

}
}
class B extends A
{
public B()
{

}
}

Special case for instanceof keyword usage that If you have a part of your system generating a multiple types of objects , you will need to know the types of these objects before you start your logic on it . The big number of times to instanceof usage in your project is a sign of low quality of software design.

Re: java instanceof keyword

Tue Jun 11, 2013 11:02 pm

updated.
  Related Posts  to : java instanceof keyword
 Java volatile keyword     -  
 Is null a keyword     -  
 What is the use of serializable keyword in C#     -  
 switch keyword in c++ usage     -  
 2d game in java-Monster-Java 2D Game Graphics and Animation     -  
 what is java     -  
 java     -  
 Java course     -  
 What is Java API?!!!     -  
 java or .net     -  

Topic Tags

Java Basics, Java Keywords