The blog of Jafar Aliyev

Archive

Creation date:

Use instanceof carefully

interface MyInterface{}
class A{}
public class B{
   public static void main(String[] args) {
     B b = new B();
     if (b instanceof MyInterface){
       System.out.println("b is MyInterface");
     }
   }
}

This code will compile. Althougt the condition b instanceof MyInterface will not succeed the code will compile. But when we add the following condition:

if (b instanceof A){
  System.out.println("b is A");
}

compilation fails. The class B must be on the same path of inheritance tree with class A. In order to make such comparision class B must be subclass of A, or class A must be subclass of B. If we add extends A to the declaration of class B the condition b instanceof A will return true. If we add extends B to the declaration of class A, the condition b instanceof A will not succeed, but in both cases compilation will succeed.

For interfaces there are not such restriction. You can check an instance of any class against any interface.

Author: Jafar N.Aliyev (Jsoft)

Read also

Java access and nonaccess modifiers
Look at this cheat sheet for Java access and nonaccess modifiers

Static methods can not be overriden
Here I explain, why static methods can not be overriden

© Copyright

All articles in this site are written by Jafar N.Aliyev. Reproducing of any article must be followed by the author name and link to the site of origin(this site). This site also keeps the same rules relative to the articles of other authors.