久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

java - 使用匿名類實(shí)例化了一個(gè)抽象類之后,如何重寫其中的抽象方法并調(diào)用?

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

問(wèn)題描述

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()呢? 創(chuàng)建rhythm對(duì)象是可以用匿名類的方法實(shí)例化的,那是實(shí)例化之后 想調(diào)用一個(gè)重寫的getDuration()方法,有什么辦法么?在不引入子類繼承的前提下。

問(wèn)題解答

回答1:

java不能怎么做,但能用內(nèi)部類變相的實(shí)現(xiàn)這個(gè)需求

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 把實(shí)現(xiàn)放到這里return 0; }});rhythm.perform();note.getNoteValue();noteCallback.notePlayed(note); }回答2:

做不了吧,如果能做Java豈不是動(dòng)態(tài)語(yǔ)言了?

標(biāo)簽: java
主站蜘蛛池模板: 呈贡县| 乌拉特后旗| 叙永县| 丘北县| 灵石县| 三明市| 岳西县| 乌兰浩特市| 大丰市| 达日县| 临夏县| 利川市| 江西省| 城固县| 麟游县| 孟州市| 育儿| 眉山市| 蒙城县| 中方县| 稷山县| 曲阜市| 循化| 筠连县| 卓尼县| 若尔盖县| 邯郸县| 武强县| 英吉沙县| 临城县| 庆阳市| 赤城县| 高清| 普定县| 韶山市| 新昌县| 庆城县| 邵阳县| 通渭县| 泗阳县| 龙州县|