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

using instanceof with upcastedreferences & Interfaces

Ameet Parande

Joined: Sep 10, 2003
Posts: 7
Check this program:
class A { }
class B extends A { }
class C extends B { }
class D extends C implements foo { }
class mox
public static void test( D d )
System.out.println( "Testing A = " + ((A) d) instanceof foo );
System.out.println( "Testing B = " + ((B) d) instanceof foo );
System.out.println( "Testing C = " + ((C) d) instanceof foo );
System.out.println( "Testing D = " + d instanceof foo );

public static void main( String [] args )
D d = new D();
test( d );
I was excpcting the output to be: false, false, false, true
But I got: true, true, true, true
If Classes A, B and C do not directly implement the interface why should it logically be an instance of that interface?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Welcome to JavaRanch!
A Java cast doesn't do anything to change an object, just tells the compiler how to treat a reference to an object. Casts are confirmed at runtime, but even then, they do nothing to change the object (unlike C++ casts, which can modify pointers.)
The instanceof operator looks at an object at runtime, and determines if it has a certain type or not. Regardless of what type the object has been cast to, this information is always available. There's no way to "hide the foo nature" of a D object -- not using casting, nor any other way.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: using instanceof with upcastedreferences & Interfaces
jQuery in Action, 3rd edition