• 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

Instanceof

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
interface I{}
class A {}
class D{}

class InstOfTest{
public static void main(String args[]){

Boolean b;
b = new A() instanceof I ;

b = new A() instanceof D ;

}
}

In above code class A is not implemented Interface I.

But the statement
b = new A() instanceof I
is not generating compilation error


But the code
b = new A() instanceof D ;

is generating error.why?
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

But the statement
b = new A() instanceof I
is not generating compilation error



This is because it is theoretically possible for a new class, say class A1, to subclass the A class and implement I. And since, A1 IS-A A, this will be a case where A is a instanceof I.

Now, in this example, it is not possible, as A is actually instantiated on the same line. But the compiler is not smart enough to figure out -- maybe it will with future releases.

But the code
b = new A() instanceof D ;

is generating error.why?



Since A and D are not super/sub classes of each other, there is no way one could be an instance of the other. (since multiple inheritance is not supported with Java)... So the compiler is smart enough to know that this statement will always be false, hence useless. (hence, compile error)

Henry
 
Proudly marching to the beat of a different kettle of fish... while reading this tiny ad
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic