《java編程思想》——內部類


內部類

能夠將一個類的定義放在另外一個類定義內部,這就是內部類。

 

建立內部類

//建立內部類且在外部類的一個方法返回一個指向內部類的引用
public class Parcel2 {
    //內部類Contents
    class Contents {
        private int i = 11;

        public int value() {
            return i;
        }
    }
    //內部類Destination
    class Destination {
        private String label;

        public Destination(String whereTO) {
            this.label = whereTO;
        }

        String readLabel() {
            return label;
        }
    }
    //返回指向內部類的引用
    public Destination whereTo(String s){
        return  new Destination(s);
    }
    //返回指向內部類的引用
    public Contents contents(){
       return new Contents();
    }

    public void ship(String desc) {
        //Contents內部類實例
        Contents c = contents();
        //Destination內部類實例
        Destination d = whereTo(desc);
        System.out.println(d.readLabel());
    }

    public static void main(String[] args) {
        Parcel2 p = new Parcel2();
        p.ship("Tasmania");

        Parcel2 q = new Parcel2();
        //若是想從外部類的非靜態方法以外的任意位置建立某個內部類的
        //對象,那麼就必須像下面的例子指明這個對象的類型:OuterClassName.InnerClassName
        Parcel2.Contents c = q.contents();
        Parcel2.Destination d = q.whereTo("from");
        System.out.println(d.readLabel());
    }
}

鏈接到外部類

//迭代器
public interface Selector {
    boolean end();

    Object current();

    void next();
}

public class Sequence {
    //items和next爲外部類
    private Object[] items;
    private int next = 0;

    public Sequence(int size) {
        items = new Object[size];
    }

    public void add(Object x) {
        if (next < items.length) {
            items[next++] = x;
        }
    }

    private class SequenceSelector implements Selector {
        private int i = 0;

        public boolean end() {
            return i == items.length;
        }

        public Object current() {
            return items[i];
        }

        public void next() {
            if (i < items.length) {
                i++;
            }
        }
    }

    public Selector selector() {
        return new SequenceSelector();
    }

    public static void main(String[] args) {
        Sequence sequence = new Sequence(10);
        for(int i = 0; i < 10 ;i++){
            sequence.add(Integer.toString(i));
        }
        Selector selector = sequence.selector();
        while (!selector.end()){
            System.out.println(selector.current() + "");
            selector.next();
        }
    }
}

內部類擁有對其外部類全部成員的訪問權(就好像本身擁有這些成員同樣),如何作到呢?
    當某個外部類的對象建立了一個內部類對象時,此內部類對象一定會祕密地捕獲一個指向那個外圍類對象的引用,而後當訪問此外部類成員的時,就用那個引用選擇外圍類的成員.

使用.this與.new

內部類與向上轉型

在方法和做用域內的內部類

匿名內部類

嵌套類

接口內部類

爲何須要內部類

內部類的繼承

局部內部類

內部類能夠被覆蓋嗎?

相關文章
相關標籤/搜索