嵌套类包括:
1.静态成员嵌套类:可视为外部类的静态方法,可访问外部类的静态属性和方法。
2.成员嵌套类:可视为外部类的成员方法,可访问外部类的所有成员属性和方法。成员嵌套类的对象一定会和外部类的对象关联,如下两者将关联在一起(成员嵌套类可通过Outer.this访问所关联的外部类对象):
Outer.Inner inner=new Outer().new Inner();
3.匿名嵌套类:可视为外部类的局部变量,可访问外部类的所有成员属性和方法,以及使用final修饰的局部变量
4.局部嵌套类:同匿名嵌套类
使用原则:
1.如果嵌套类不需要访问外部类对象,那么应使用静态成员嵌套类,以便GC能及时回收
2.在外部类的方法里,如果已存在相应的类型,那么应优先使用匿名嵌套类
3.匿名嵌套类和局部嵌套类应保持较少的代码量
4.谨慎使用public,protected修饰嵌套类
用法举例:
1.静态成员嵌套类可作为帮助类
public class Layout {
private LayoutParams layoutParams;
public LayoutParams getLayoutParams() {
return layoutParams;
}
public void setLayoutParams(LayoutParams layoutParams) {
this.layoutParams = layoutParams;
}
//使用静态嵌套类提供布局参数
public static class LayoutParams{
private int width;
private int height;
//特殊的布局参数
public static int MATCH_PARENT=-1;
public static int WRAP_CONTENT=-2;
public LayoutParams(int width,int height){
this.width=width;
this.height=height;
}
}
}
2.使用成员嵌套类实现多个接口
interface Singer{
void sing();
}
interface SongWriter{
void write();
}
//Person可能同时是歌手和作曲家
public class Person implements Singer,SongWriter{
private String name;
private Singer singer;
private SongWriter songWriter;
public Person(String name){
this.name=name;
this.singer=new SingerImpl();
this.songWriter=new SongWriterImpl();
}
public void sing() {
singer.sing();
}
public void write() {
songWriter.write();
}
private class SingerImpl implements Singer{
public void sing() {
System.out.println(name+"is singing!!!");
}
}
private class SongWriterImpl implements SongWriter{
public void write() {
System.out.println(name+"is writing!!!");
}
}
}