This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance of Operator

 
carol souza
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
m2(myA);
}
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,
Carol






 
Sridhar Gudipalli
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Carol, Welcome to JavaRanch!!

Please try to compile the below code and try to evaluate yourself.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic