Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof doubt

 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
interface intf { }

class test {}

class test1
{
public static void main(String[] args)
{
test1 tt = new test1();
System.out.println(tt instanceof intf);// No compiler time error
System.out.println(tt instanceof test); // Compiler time error
}
}

When class is not inherting another class then instanceof throws compile time error

When class is not inherting another interface then instanceof not throwing compile time error

can anybody explain why..??

 
Saurabh Khanna
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vidya Sagar

At compile time, the compiler checks that if each of the left hand and right hand operands of the instanceof operator can denote a common subtype of both the operands, if not then they have no obvious relations and compiler throws an error.

taking the above examples:

tt instanceof intf

If we create a class which is subtype of both of above, any of the above references will be able to denote that subtype, but:

tt instanceof test

if we create a class which is common subtype of both of above (which we really can't because multiple inheritence is not allowed in Java), both of references above will not be able to denote that subtype...

Hope this helps...

- Saurabh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic