内部类
class A{
calss B{
}
}
定义在类内部的类编译后产生的文件为A.class和A$B.class
语法
外部类.内部类 对象名 = new 外部类(). new 内部类();
内部类可以使用外部类的成员变量。每一个内部类的对象和外部类对象相关联。但是使用时发现如果外部和内部各自新建对象内部类使用外部类变量值,外部变量值为0。解决方法:直接引用外部类的对象,建立在一个内存上。
public class A{
i = 0;
class B{
int j ;
int fun(){
int result = i + j;
System.out.println(i + "" + j);
return result;
}
}
}
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 = 2;
b.j = 5;
int result = b.fun();
System.out.println(result);
}
}
匿名内部类
class Test{
public static void main(String[] args){
//AImpl al = new AImpl();
//A a =al;
B b = new B();
b.fun(new A(){
public void doSomething(){
System.out.println("匿名内部类");
}
});
}
}
作用:实现A的接口。