Student: One thing I find really confusing is when we store a subclass object in a superclass variable. Is there any way to tell which type the object actually is?
Prof: There is in fact! Check it out, we can use it on our old friend,
Pict:Prof: So it tells us that
c is in fact a Circle, and is not a Rect, from our program.Student: Huh, that’s interesting. What would
c instanceof Pict say?Prof: Let’s try a few more:
Student: Huh, interesting. So does it work for
extends, too?Prof: Indeed!
Student: OK, so how does that work? Does it like… search the class diagram?
Prof: Exactly.
a instanceof C starts at the class of the object in a. If that isn’t C, it checks that class’s superclass and anything it implements, all the way up the diagram, looking for C. If a instanceof C, then the value stored in a could be stored in a variable of type C.Student: Cool, where do I use that?
Prof: Honestly? Mostly you don’t.
Student: Mostly I don’t? What do you mean?
Prof: Well, most of the time we try to make our programs work out using the general interface types, like
Pict or Place, for most variables. Then we just rely on the methods defined on them being present. Field lookups and class-specific work happen inside the class, and calling a method will select the class for the right object. So instanceof is honestly not needed much in well-written code.Student: Hm… then why’d you show me?
Prof: Well, you’ll still see it in some places. And we need it to wrap up some of our discussion of
Object and equals.Practice
Using these classes, is each instanceof true or false?
interface Place {}
class Location implements Place {}
class Park extends Location {}
class DogPark extends Park {}
class BusStop extends Location {}
Place p = new Park();
Location loc = new DogPark();Object
Location
Park
DogPark
BusStop
interface
Place
p instanceof Place is p instanceof Location is p instanceof DogPark is p instanceof BusStop is loc instanceof Park is With the same classes, what is
new Location() instanceof Park?falseThe search starts at the object’s own class,Location, and only goes up from there: toPlaceandObject.Parkis belowLocation, so it never comes up.true, becauseParkextendsLocationThe arrow fromParktoLocationsays everyParkis aLocation. It doesn’t say everyLocationis aPark.- It doesn’t compileA
Locationvariable could hold aPark, so Java lets you ask. It refuses only when the answer could never betrue.