Switch to full style
General Java code examples
Post a reply

java instanceof keyword

Fri Jan 30, 2009 1: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

Wed Jun 12, 2013 12:02 am

updated.

Post a reply
  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     -  
 Java course     -  
 What is Java API?!!!     -  
 java or .net     -  
 need help in java     -  
 Using FTP in java     -  

Topic Tags

Java Basics, Java Keywords