1. 程式人生 > >java中巢狀介面

java中巢狀介面

介面知識點

      1、介面中定義的變數預設是public static final 型,且必須給其初值,所以實現類中不能重新定義,也不能改變其值
      2、介面中的方法預設都是 public abstract 型別的:
      3、介面預設也是abstract的的:public abstract interface xx ===public interface xx
public interface AreaInterface{
     double pai=Math.PI;
     double area();
     interface Neibujiekou{
          viod menthod();
     }
}
public abstract interface AreaInterface{
     public static final double pai  = Math,.PI;
     public abstract double area();
}

巢狀介面

       在Java語言中,介面可以巢狀在類或其它介面中。由於Java中interface內是不可以巢狀class的,所以介面的巢狀就共有兩種方式:class巢狀interface、interface巢狀interface。
       1. class巢狀interface
       這時介面可以是public,private和package的。重點在private上,被定義為私有的介面只能在介面所在的類被實現。可以被實現為public的類也可以被實現為private的類。當被實現為public時,只能在被自身所在的類內部使用。只能夠實現介面中的方法,在外部不能像正常類那樣上傳為介面型別。
class A {
    private interface D {
        void f();
    }
    private class DImp implements D {
        public void f() {}
    }
    public class DImp2 implements D {
        public void f() {}
    }
    public D getD() { return new DImp2(); }
    private D dRef;
    public void receiveD(D d) {
        dRef = d;
        dRef.f();
    }
}

public class NestingInterfaces {
    public static void main(String[] args) {
        A a = new A();
        //The type A.D is not visible
        //! A.D ad = a.getD();
        //Cannot convert from A.D to A.DImp2
        //! A.DImp2 di2 = a.getD();
        //The type A.D is not visible
        //! a.getD().f();        
        A a2 = new A();
        a2.receiveD(a.getD());
    }
}
       其中語句A.D ad = a.getD()和a.getD().f()的編譯錯誤是因為D是A的私有介面,不能在外部被訪問。語句A.DImp2 di2 = a.getD()的錯誤是因為getD方法的返回型別為D,不能自動向下轉型為DImp2型別。

       2. interface巢狀interface
      由於介面的元素必須是public的,所以被巢狀的介面自動就是public的,而不能定義成private的。在實現這種巢狀時,不必實現被巢狀的介面
classCircle implements  AreaInterface{
    //只需實現area();不用實現menthod();
    double area(){}
}
class Circle implements AreaInterface,AreaInterface.Neibujiekou{
    double area(){}
    viod menthod(){}
}