• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

using instanceof with upcastedreferences & Interfaces

Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
author and iconoclast
Posts: 24203
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
    Bookmark Topic Watch Topic
  • New Topic