一、内部类
1.定义
class A {
int i;
class B {
int j;
int funB(){
int result = i+j; //完整写法A.this.i
return result;
}
}
}
生成内部类对象:
A a = new A();
A.B b = a.new B(); //初始化内部类A.B b = new A() .new B();
a.i = 3;
b.j = 1;
int result = b.funB();
System.out.println(result);
interface A{
public void doSomething();
}
class B{
public void fun(A a) {
System.out.println("B类的fun函数");
a.doSomething();
}
}
class AImp1 implements A{
public void doSomething(){
System.out.println("doSomething");
}
}
AImp1 al = new AImp1();
A a = al;
B b = new B();
b.fun(a);
//使用匿名内部类
b.fun(new A(){
public void doSomething(){
System.out.println("匿名内部类");
}
});