成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

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

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

瀏覽:153日期: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();//想在這里重寫(xiě)getDuration方法,如何做到? rhythm.perform(); note.getNoteValue(); noteCallback.notePlayed(note);}

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

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

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

問(wèn)題解答

回答1:

java不能怎么做,但能用內(nèi)部類(lè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();//想在這里重寫(xiě)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