Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures Getting There Type Casting

Lakshmi Narayana Dasari
Lakshmi Narayana Dasari
1,185 Points

Functioning of intsanceof in this code.

I am bit confused with the ise of instanceof. For example:

Mountain m = new Mountain(); Object obj; if(obj instanceof Mountain) // here obj is not an instanceof mountain but how does this block executes. { Mountain mou = (Mountain)obj; }

1 Answer

Corey Johnson
PLUS
Corey Johnson
Courses Plus Student 10,192 Points

You are correct. In your example, obj is not an instance of Mountain. If we use just your code.. obj would be null.

But if we work within the context of the lesson you just completed.. and we have a method that takes an Object as a parameter.. instanceof would work fine. Consider the following code:

Mountain mountain = new Mountain();
System.out.println(isMountain(mountain));

public boolean isMountain(Object obj) {
    if(obj instanceof Mountain) return true;
    else return false;
}

In this case.. the return result from isMountain would be true.

If i took your example code above.. it would need to be something like this.. for obj to be an instance of Mountain:

Mountain m = new Mountain(); 
Object obj = m; // this is the important part.. now obj is a Mountain object.
if(obj instanceof Mountain) 
{ 
    Mountain mou = (Mountain)obj; 
}

In this example.. we are "up casting" so you do not have to explicitly cast the "m" object to Mountain when assigning it to "obj"

Hope this helps!