File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes instanceof confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instanceof confusion" Watch "instanceof confusion" New topic

instanceof confusion

Mark Henryson
Ranch Hand

Joined: Jul 11, 2005
Posts: 200

The above coding is very confusing to me. No problem in the operators used in the above program. I know the precedence and how the &&,&,|| and | will work.

All my confusion is in instanceof thing!!
What the below things are exactly mean?

1. (a1 = new D()) instanceOf C
2. a2 = new B()) instanceof A
3. a2 instanceof B
4. a3 = new C()) instanceof A
marc weber

Joined: Aug 31, 2004
Posts: 11343

any instance of B is also an instance of A, and
any instance of D is also an instance of A, and
any instance of C is also an instance of B, and
any instance of C is also an instance of A.

According to the Java Language Specification, "the result of the instanceof operator is true if the value of the ... [first operand, which must be a reference] is not null and the reference could be cast (�15.16) to the ... [second operand, which must be a type] without raising a ClassCastException. Otherwise the result is false." (The bold is mine.)

"a1 = new D()" creates a new instance of type D, and assigns it to a variable of type A (an upcast). So, "(a1 = new D()) instanceof C" returns false, because the true runtime type of a1 is D, and an instance of D is not an instance of C. In particular, a reference to an instance of D cannot be cast to type C without a ClassCastException.

Now, here's the trick: Because this evaluates to false, the second boolean is not evaluated due to short-circuiting of the && operator. In particular, "a2 = new B()" does not execute, and a2 remains a null reference. Therefore, "a2 instance of B" actually returns false.

[ August 23, 2005: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
There are situations where you have a general type and need something more specific. Consider a method that counts ten-speed bikes but it gets a list containing all different makes and models.

There is no "type" attribute in Bike so you are stuck testing the type using instanceof. Any TenSpeed or any bike that inherits TenSpeed will be counted. If a Buzzard inherits from Bird then Buzzard IS-A bird.]]
[ August 22, 2005: Message edited by: Rick O'Shay ]
I agree. Here's the link:
subject: instanceof confusion
It's not a secret anymore!