1. 程式人生 > >成員內部類 與 區域性內部類的實現

成員內部類 與 區域性內部類的實現

定義一個樂器(Instrument)介面,其中有抽象方法 void play();在InstrumentTest類中,定義一個方法 void playInstrument(Instrument ins); 並在該類的main方法中呼叫該方法。
要求:分別使用下列內部類完成此題。
成員內部類
區域性內部類

public interface Instrument {//定義Instrument介面
 void play();
}
public class InstrumentTest { //成員內部類的實現
  class instrument1 implements Instrument{
    public void play(){
     System.out.println("彈奏吉他!");
     }
     }
  public void playInstrument(Instrument ins){
     ins.play();
     }
  //區域性內部類的實現
  public Instrument  test1(){
      class Piano implements Instrument{
       public void play() {
         System.out.println("演奏鋼琴!");
       }     
      }
      return  new Piano(); 
  }
  public static void main(String[] args) {
InstrumentTest test = new InstrumentTest();//建立外部類物件
InstrumentTest.instrument1 inner= test.new instrument1();//建立內部類物件[此處是成員內部類物件的建立]
     test.playInstrument(inner);`在這裡插入程式碼片`
  InstrumentTest  t = new InstrumentTest();//建立類物件[此處是區域性內部類物件的建立]
  test.playInstrument(  t.test1());
  }
}