Advertisement
  1. Code
  2. Mobile Development
  3. Android Development

Learn Java for Android Development: Checking Object Type with Instanceof

Scroll to top
Read Time: 4 min
This post is part of a series called Learn Java for Android Development.
Learn Java for Android Development: Java Syntax
Learn Java for Android Development: Working with Arrays

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:

1
2
if(iVar==0) {
3
    // variable is zero
4
} else if (iVar > 0) {
5
    // variable is a positive number
6
} else {
7
    // variable is a negative number
8
}

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:

1
2
SaltwaterFish nemo = new SaltwaterFish();
3
if(nemo instanceof Fish) {
4
    // we’ve got some sort of Fish
5
    // could be a Fish (parent class), or subclass of some kind, like
6
    // SaltwaterFish, or FreshwaterFish. 
7
8
    if(nemo instanceof SaltwaterFish) {
9
        // Nemo is a Saltwater fish!
10
    }
11
}

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:

1
2
3
void checkforTextView(View v)
4
{
5
     if(v instanceof TextView) 
6
    {
7
        // This is a TextView control
8
    } else {
9
        // This is not a TextView control
10
    }
11
}

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.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.