java內部類面試題介面程式設計題
阿新 • • 發佈:2018-10-31
1、內部類的形式是怎樣的?
⒈靜態內部類
⒉成員內部類
⒊區域性內部類
⒋匿名內部類
2、為什麼要有“內部類”?
1、內部類提供了更好的封裝。只能讓外部類直接訪問,不允許同一個包中的其他類直接訪問。
2、內部類可以直接訪問外部類的私有屬性,內部類被當成其外部類成員。但外部類不能訪問內部類的內部屬性。
3、利用內部類可以方便實現哪些功能?
可以不受限制的訪問外部類的域和方法。
4、內部類的實現機制?
可以,限制,如果是靜態內部類,不能訪問外部類的非靜態成員。
程式設計題:
1.定義一個樂器(Instrument)介面,其中有抽象方法
void play();
在InstrumentTest類中,定義一個方法
void playInstrument(Instrument ins);
並在該類的main方法中呼叫該方法。
要求:分別使用下列內部類完成此題。
成員內部類
區域性內部類
匿名類
//使用成員內部類實現 package xianweifu; interface Instrument{ public abstract void play(); } class InstrumentTest{ class Inner1 implements Instrument{ public void play(){ System.out.println("演奏鋼琴"); } } public void playInstrument(Instrument ins){ ins.play(); } } public class demo8 { public static void main(String[] args) { InstrumentTest test = new InstrumentTest();//建立外部類物件 InstrumentTest.Inner1 inner= test.new Inner1();//建立內部類物件 test.playInstrument(inner); } }
//使用區域性內部類實現 package xianweifu; interface Instrument{ public abstract void play(); } class InstrumentTest{ public void tell(){ class Piano implements Instrument{ public void play() { System.out.println("演奏鋼琴"); } } Instrument piano = new Piano(); piano.play(); } public void playInstrument(Instrument ins){ ins.play(); } } public class demo8 { public static void main(String[] args) { InstrumentTest test = new InstrumentTest();//建立類物件 test.tell(); } }
2、定義一個Father和Child類,並進行測試。//使用匿名內部類實現 package xianweifu; interface Instrument{ public abstract void play(); } class InstrumentTest{ public void playInstrument(Instrument ins){ ins.play(); } } public class demo8 { public static void main(String[] args) { InstrumentTest test = new InstrumentTest();//建立類物件 test.playInstrument(new Instrument(){ public void play(){ System.out.println("彈奏鋼琴"); } }); } }
要求如下:
1)Father類為外部類,類中定義一個私有的String型別的屬性name,name的值為“zhangjun”。 2)Child類為Father類的內部類,其中定義一個introFather()方法,方法中呼叫Father類的name屬性。
3)定義一個測試類Test,在Test類的main()方法中,建立Child物件,並呼叫introFather ()方法。
package xianweifu;
class Father {
private String name = "zhangjun";
class Child {
public void introFather() {
System.out.println("father's name:" + name);
}
}
}
public class demo8 {
public static void main(String[] args) {
Father child = new Father();
Father.Child test = child.new Child();
test.introFather();
}
}