lambda和抽象類


lambda的使用條件是‘一個接口僅有一個待實現的方法’;

so,lambda不能使用在抽象類上,使用后或提示‘Target type of a lambda conversion must be an interface

非要使用,需要變通;

例如,抽象類 TimerTask

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    System.out.println("99999");
}, 1000);

在這里用lambda的話就會報錯,但可以把Timer拓展一下

public class MyTimer extends Timer {
 
    public TimerTask schedule(final Runnable r, long delay) {
        final TimerTask task = new TimerTask() { public void run() { r.run(); }};
        this.schedule(task, delay);
        return task;
    }
}

然后使用MyTimer

MyTimer timer = new MyTimer();
timer.schedule(()->{
   System.out.println("99999");
}, 1000); 
timer.schedule(
this::run, 1000);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM