Tutorial Details
- Technology: Java with Android Focus
- Difficulty: Beginner
- Estimated Completion Time: 15 minutes
- Learn Java for Android Development: Introduction to Java
- Learn Java for Android Development: Java Syntax
- Learn Java for Android Development: Checking Object Type with Instanceof
- Learn Java for Android Development: Working with Arrays
- Learn Java for Android Development: Reflection Basics
- Learn Java for Android Challenge: Iteration
- Learn Java for Android Development: Inner Classes
- Learn Java for Android Development: More On Inner Classes
- Learn Java for Android Development: Javadoc Code Documentation
- Learn Java for Android Development: String Basics
- Learn Java for Android Development: Date and Time Basics
- Learn Java for Android Challenge: Strings
- Learn Java for Android Development: Java Shorthand
This quick lesson in our Learn Java for Android Development series shows you how to conditionally check the type of an object using the instanceof keyword in Java.
Basic Conditionals
We talked about many of the basic Java conditional statements in the Learn Java for Android Development: Java Syntax tutorial. For example, Java provides all the typical conditional operators one might expect, including those to check for equality, inequality, greater than, less than, etc.
Here’s some Java code that checks the value of a numeric variable (called iVar) and provides different code paths depending on whether the value of iVar is zero, negative or positive:
if(iVar==0) {
// variable is zero
} else if (iVar > 0) {
// variable is a positive number
} else {
// variable is a negative number
}
Using instanceof in Conditional Statements
Now let’s look at a specific Java feature you can also use in conditional statements. Because Java is a fully object oriented language, you can also test if an object is of a specific type (an instance of a specific class) conditionally using the instanceof keyword. The instanceof keyword is a Boolean operator, used like a regular mathematical Boolean conditional operator to generate a true or a false result.
Let’s look at a quick example. Let’s assume we have a parent class called Fish, which has two derived subclasses: SaltwaterFish and FreshwaterFish. We could use the instanceof keyword to test if an object is an instance of a specific class (or subclass) by name:
SaltwaterFish nemo = new SaltwaterFish();
if(nemo instanceof Fish) {
// we’ve got some sort of Fish
// could be a Fish (parent class), or subclass of some kind, like
// SaltwaterFish, or FreshwaterFish.
if(nemo instanceof SaltwaterFish) {
// Nemo is a Saltwater fish!
}
}
Using instanceof in Android Development
So, when it comes to Android development, when is the instanceof feature useful? Well, for starters, the Android SDK classes are organized in typical object oriented fashion: hierarchically. For example, the classes such as Button, TextView, and CheckBox, which represent different types of user interface controls, are all derived from the same parent class: View. Therefore, if you wanted to create a method that took a View parameter, but had different behavior depending upon the specific type of control, you could use the instanceof mechanism to check the incoming parameter and determine exactly what kind of view control had been passed in.
For example, the following method takes a View parameter, allowing you to pass in any type of View, but specifically singles out TextView controls for special processing:
void checkforTextView(View v)
{
if(v instanceof TextView)
{
// This is a TextView control
} else {
// This is not a TextView control
}
}
In this example, we might continue by making a call to a method that is only valid for a TextView object and not the generic View object—in which case, we would likely cast the View parameter to a TextView prior to making such a call. If, however, we wanted to make a call that is available in all View objects, but behaves differently in TextView objects, there is no need to test for this. Java will handle calling the appropriate version of the method specific to TextView. This is one of the great features of object-oriented programming: the most appropriate version of a given method is called.
Conclusion
In this quick lesson you have learned how to use the instanceof Java keyword to check the type of an object at runtime and provide conditional code paths based on the result. This is a handy Java feature that Android developers often rely upon, since the Android SDK is organized hierarchically.
About the Authors
Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams TeachYourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.




It is great to know that instanceof operator exists, but it is better not to misuse instanceof. Generally, object oriented design should try to avoid using instanceof.
You have to realize that using instanceof can be a great indication of a poor object oriented design. If you are finding yourself using it, try to think multiple of times why you have to do that. It is probably time to look at your design and figure out a better approach.
There are some acceptable places to use instanceof, such as within overriding equals() so that you can preserve the contract (symmetry and transitivity).
A simple way to avoid instanceof is to using polymorphism or even a better design (such as perhaps enums play a better role)
Just be careful when you use instanceof.
This may be in Android cathegory, not in iPhone, I guess… :P
Great catch, now resolved. Thanks for pointing that out!
Why is camelCase so widespread, but instanceof is never instanceOf ????