6.2 接口的例子

本文介绍了Java中接口的概念及应用,包括回调函数的实现方式,并通过具体例子讲解了Comparator接口的使用方法。此外,还探讨了对象克隆的重要性和深浅拷贝的区别。

1 接口和回调函数

回调函数给程序添加了极大的灵活性,而接口可以实现回调函数。

回调函数就是把一系列动作方法打包起来,等到该调用的时候调用。

public interface ActionListener
{
    void actionPerformed(ActionEvent event);
}
class TimePrinter implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
        System.out.println("At the tone, the time is " + new Date());
        Toolkit.getDefaultToolkit().beep();
    }
}
ActionListener listener = new TimePrinter();
Timer t = new Timer(10000, listener);
t.start();

2 Comparator 接口

public interface Comparator<T>
{
    int compare(T first, T second);
}
class LengthComparator implements Comparator<String>
{
    public int compare(String first, String second) 
    {
        return first.length() - second.length();
    }
}
Comparator<String> comp = new LengthComparator();
if (comp.compare(words[i], words[j]) > 0) ...

3 对象克隆

千万不要在程序克隆的地方出bug了。注意区分深拷贝和浅拷贝。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值