It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Instance of Operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Instance of Operator" Watch "Instance of Operator" New topic

Instance of Operator

carol souza

Joined: May 19, 2010
Posts: 1
Hi All ,

Source : SCJP 6 Study Guide by Katherine Sierra & Bert Bates .
Chapter 4 :

Example (a) :

class A { }

class B extends A {
public static void main (String [] args) {
A myA = new B();
public static void m2(A a) {
if (a instanceof B)
((B)a).doBstuff(); // downcasting an A reference
// to a B reference
public static void doBstuff() {
System.out.println("'a' refers to a B");

The preceding code compiles and produces the output:

'a' refers to a B

example (b)

interface Face { }
class Bar implements Face{ }
class Foo extends Bar { }

Output when

Bar instance when tested with Instanceof Operator against Foo class returns false

When we Compare example a and b we see that when class B extends class A
and when we test if a is an instance of b , it returns true
In the same contest in example b when class Foo extends Bar and when we
test if Bar instance is an instance of Foo , should it not return true .

Can someone please guide me what I am missing ,

Thanks in advance,

Sridhar Gudipalli
Ranch Hand

Joined: Nov 02, 2005
Posts: 120
Hi Carol, Welcome to JavaRanch!!

Please try to compile the below code and try to evaluate yourself.

Sridhar Gudipalli|SCJP 6.0
SCWCD objectives
I agree. Here's the link:
subject: Instance of Operator
It's not a secret anymore!