File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance of Operator

 
carol souza
Greenhorn
Posts: 1
  • 0
  • 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
  • 0
  • 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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic