File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

using instanceof with upcastedreferences & Interfaces

 
Ameet Parande
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic