• 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 ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

instances not,but instanceof is

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Q-1>
interface I{}
interface J{}
class C implements I{}
class D extends C implements J{}
class MyClass
{
public static void main(String args[])
{
I x = new D();
if( x instanceof J) System.out.println("J");
}
}
I am getting output as J.
My question is how x can be an instance of J?
x could be an instance of C as it implements I.
x could be an instance of D as it implements I.
But i can't assume instance of I refer to an an instance of J as they are not directly elated.Plz help
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
the instanceof operator uses the runtime type of the left operand and compares it with the type on the right operand.
From JLS 15.20.2 Type Comparison Operator instanceof


At run time, the result of the instanceof operator is true if the value of the RelationalExpression (left operand) is not null and the reference could be cast (�15.16) to the ReferenceType (right operand) without raising a ClassCastException. Otherwise the result is false.


Let's analyze your example:
I x = new D();
The compile-time type of x is I.
The runtime types of x can be D, C, J and I (and Object).
You can cast x to J without getting a ClassCastException since x is actually of type J, and thus, the instanceof statement yields true and "J" is printed.
[ March 21, 2002: Message edited by: Valentin Crettaz ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic