版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Bubble1210/article/details/50733609
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();
}
}
//使用匿名内部类实现
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("弹奏钢琴");
}
});
}
}
2、定义一个Father和Child类,并进行测试。
要求如下:
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();
}
}