第35集 内部类和匿名内部类
主要内容:
1.什么是内部类.
2.内部类的使用方法.
3.匿名内部类的使用方法:
主要通过程序来说明它的用法:
程序1:内部内的定义
生成内部类对象:
程序2:匿名内部类
注意到它后面有一对'{ }',这想当于一个类,实现了这个接口,而类是可以new的。
主要内容:
1.什么是内部类.
2.内部类的使用方法.
3.匿名内部类的使用方法:
主要通过程序来说明它的用法:
程序1:内部内的定义
class A{
int i;
class B{
int j;
//内部类是可以随意使用外部类的成员变量
int funB(){
//int result = i + j;
int result = A.this.i + this.j;
return result;
}
}
}
编译之后,会生成两个类:A.class 及 A$B.class。
生成内部类对象:
class Test{
public static void main(String args[]){
A a = new A();
//A.B b = new A().new B();
A.B b = a.new B();
a.i = 3;
b.j = 1;
int result = b.funB();
System.out.println(result);
}
}
程序2:匿名内部类
//*************************************************************//
interface A{
public void doSomething();
}
//*************************************************************//
class B{
public void fun(A a)
System.out.println("B 类的fun函数 ");
b.doSomething();
}
}
//*************************************************************//
//A的实现类
class AImpl implements A{
public void doSomething(){
System.out.println("doSomething");
}
}
//*************************************************************//
class TestBC {
public static void main(String args[]){
/* AImpl al = new AImpl();
A a = al;
B b = new B();
b.fun(a);*/
B b = new B();
b.fun(new A(){
public void doSomething(){
System.out.println("匿名内部类");
}
}
);
}
}
b.fun( ) 它需要一个A类的对象作为参数,这里 b.fun(new A()) A是一个接口,按理说接口是抽象的 不能生成对象,即不能new。那这里怎么可以呢?
注意到它后面有一对'{ }',这想当于一个类,实现了这个接口,而类是可以new的。