「Java」「Interface」 instanceof來判斷是否有實作interface

Given:
interface Interface{
 //Interface inter1 = new Super();//錯誤,Cannot convert Super to Interface
 //Super sup1 = new Interface();//錯誤,Cannot convert Interface to Super

}
class Super{
 //Interface inter1 = new Super();//正確,假如父類別繼承Interface
 //Super sup1 = new Interface();//錯誤,Cannot convert Interface to Super

}
public class Sub extends Super implements Interface{
 public static void main(String[] args) {
  Interface inter = new Sub();
  System.out.println(inter instanceof Object);
  System.out.println(inter instanceof Interface);
  System.out.println(inter instanceof Super);
  System.out.println(inter instanceof Sub);
  Super sup = new Sub();
  System.out.println(sup instanceof Object);
  System.out.println(sup instanceof Interface);
  System.out.println(sup instanceof Super);
  System.out.println(sup instanceof Sub);
  Sub sub = new Sub();
  System.out.println(sub instanceof Object);
  System.out.println(sub instanceof Interface);
  System.out.println(sub instanceof Super);
  System.out.println(sub instanceof Sub);
  Interface inter1 = new Super();//錯誤,Cannot convert Super to Interface
  //但如果父類別繼承interface,此行即可編譯成功。
  
  Super sup1 = new Interface();//錯誤,Cannot convert Interface to Super
  Sub sub1 = new Interface();//錯誤,Interface is not a Sub
  Sub sub2 = new Super();//錯誤,Super is not a Sub
 }
}

留言

這個網誌中的熱門文章

[Excel]國曆轉農曆VBA

「CSS」「div區塊介紹」 三欄式網頁排版設計

「生活」眉毛觀人