Suggested Pages

Tuesday, January 31, 2017

Instance of

Instance of is a keyword that works at this way.
Suppose you have a class A and its subclass B and the following class Main.java
A.java

public class A {
 
}
class B extends A{
 
}
Main.java

public class Main {

 public static void main(String[] args) {
    A[]a=new B[1];
    A[]b=new A[1];
    System.out.println(a instanceof A[]);
    System.out.println(a instanceof B[]);
    System.out.println(b instanceof A[]);
    System.out.println(b instanceof B[]);
 }
}
The output of Main class is:
  true
  true
  true
  false
The following Main.java instead has two compiler errors. Main.java

public class Main {

   public static void main(String[] args) {
        A[]a=new B[1];
        A[]b=new A[1];
        System.out.println(a instanceof A); // Compiler Error
        System.out.println(a instanceof B); // Compiler Error
   }
}

No comments :

Post a Comment

Suggested Pages