内部类

c++ 嵌套类

C++中的嵌套类是一种类之间的关系, 不是对象之间的关系

class LinkedList
{
private:
    class Link{ // a nested class
       public:
        Link* next;
        int data;     
    };

public:
    class Iterator{
    public:
        void insert(int x);
        void erase();
    };

    LinkedList() {}
};

LinkedList::Iterator itr; // 可以这样访问类并创建对象

Java内部类

内部类的对象有一个隐式引用,它引用了实例化该内部对象的外围类对象

public class Test {
    public static void main(String[] args) {
        TalkingClock clock = new TalkingClock(1000, true);
        clock.start();

        System.out.println(clock);  // 输出      "This is an outer class!"
        TalkingClock.TimePrinter t = clock.new TimePrinter();    // 从外部建立内部类对象必须通过外部类对象
        t.changeDescription("Change");
        System.out.println(clock);   输出    "Change"

        JOptionPane.showMessageDialog(null, "Quit program?"); // 进入事件等待模式
        System.exit(0);
    }
}

class TalkingClock {
    private int interval;
    private boolean beep;
    private String description = "This is an outer class!";     

    public TalkingClock(int interval, boolean beep) {
        this.interval = interval;
        this.beep = beep;  
    }

    @Override
    public String toString() {
        return description;
    }  

    public void start() {
        ActionListener listener = new TimePrinter();
        Timer t = new Timer(interval, listener);
        t.start();
    }

    public class TimePrinter implements ActionListener {

        public void changeDescription(String description){
            TalkingClock.this.description = description;
        }  
       // 当前内部类对象中,this 依旧本类对象引用.
       // TalkingClock.this 为外围内对象引用。
        public void actionPerformed(ActionEvent event) {
            Date now = new Date();
            System.out.println("At the tone, the time is " + now);
            if (beep)
                Toolkit.getDefaultToolkit().beep();
        }
    }
}

神奇的匿名内部类

public class Test {
    public static void main(String[] args) {
        final ArrayList<String> friends = new ArrayList<>();
        friends.add("harry potter");
        friends.add("Hermione Jean Granger");
        friends.add("Ron Weasley");


        System.out.println(new ArrayList<String>(){
            {
                System.out.println(friends.toString());
                this.add("yajun yang");
                add("JG Zhang");
                add("Peng Li");
            }
        });
    }
}

输出:

[harry potter, Hermione Jean Granger, Ron Weasley]
[yajun yang, JG Zhang, Peng Li]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值