国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

java - 使用匿名類實例化了一個抽象類之后,如何重寫其中的抽象方法并調用?

瀏覽:117日期:2024-02-08 17:18:02

問題描述

public abstract class Rhythm { /** * @return duration between {@linkplain Note} in milliseconds */ public abstract long getDuration(); public void perform() {long duration = getDuration();try { Thread.sleep(duration);} catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie);} }}

--------------------------------------------------------------------

@Override public void play(Rhythm rhythm, Note note, NoteCallback noteCallback){ rhythm.getDuration();//想在這里重寫getDuration方法,如何做到? rhythm.perform(); note.getNoteValue(); noteCallback.notePlayed(note);}

--------------------------------------------------------------------

//重寫成如下形式 @Override public long getDuration(){ return (expectedMs); }

代碼附上。在play() 方法中如何直接重寫Rhythm類中的抽象方法getDuration()呢? 創建rhythm對象是可以用匿名類的方法實例化的,那是實例化之后 想調用一個重寫的getDuration()方法,有什么辦法么?在不引入子類繼承的前提下。

問題解答

回答1:

java不能怎么做,但能用內部類變相的實現這個需求

public abstract class Rhythm { /** * @return duration between {@linkplain Note} in milliseconds */ public abstract long getDuration();public abstract class InnderClass {public abstract long getDuration(); } private InnderClass innderClass; public Rhythm() {innderClass = new InnderClass() { @Override public long getDuration() {return Rhythm.this.getDuration(); }}; } public void setInnderClass(InnderClass innderClass) {this.innderClass = innderClass; } public void perform() {long duration = innderClass.getDuration();try { Thread.sleep(duration);} catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie);} }}

@Override public void play(Rhythm rhythm, Note note, NoteCallback noteCallback){//rhythm.getDuration();//想在這里重寫getDuration方法,如何做到?rhythm.setInnderClass(rhythm.new InnderClass() {@Override public long getDuration() {// TODO 把實現放到這里return 0; }});rhythm.perform();note.getNoteValue();noteCallback.notePlayed(note); }回答2:

做不了吧,如果能做Java豈不是動態語言了?

標簽: java
主站蜘蛛池模板: 巧家县| 丰台区| 南宁市| 府谷县| 东明县| 诸城市| 黔西县| 万安县| 布尔津县| 高碑店市| 康保县| 伽师县| 铜梁县| 福清市| 礼泉县| 内黄县| 中宁县| 慈溪市| 靖西县| 青铜峡市| 黎城县| 云安县| 团风县| 平南县| 沙洋县| 息烽县| 旬阳县| 临洮县| 绥宁县| 龙南县| 仙游县| 墨竹工卡县| 金平| 布尔津县| 揭阳市| 永宁县| 亳州市| 神农架林区| 吉木萨尔县| 临沭县| 兴安县|