要生成内部类的对象一定要有外部类的对象
每一个内部对象都和一个外部类相关联
内部类可以随便使用外部类成员变量和成员函数
内部类:先new一个外部类的对象,再点内部类的对象
匿名内部类:先new一个接口,再紧跟一个没有名字的类来实现接口
(1)
class A{
int i;
class B{
int j;
int funB(){
int result = i + j;
return result;
}
}
}
class Test{
public static void main(String args[]){
A a = new ();//外部类的对象
A.b b = a.new B();//内部类的对象
a.i = 3;
b.j = 1;
b.funB();
int result = b.funB();
System.out.println(result);
}
}
(2)
interface A{
public void do Something();
class B{
public void fun(A a){//B需要一个A类型的对象作为参数
System.out.println("B类的fun函数");
a.doSomething();
}
}
class AImpl implements A{
public void doSomething(){
System.out.println("doSomething");
}
}
class Test{
public static void main(String args[]){
AImpl al = new AImpl();
A a = al;
B b = new B();
b.fun(a);
}
}
Test修改如下
class Test{
public static void main(String args[]){
AImpl al = new AImpl();
A a = al;
B b = new B();
b.fun(new A//实现A的接口,A没有名字){
public void doSomething(){
System.out.println("匿名内部类");
}
}
}
}//运行结果B类的fun函数
//匿名内部类