首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

4.22 嵌套种

2013-08-10 
4.22 嵌套类Outer.Inner innernew Outer().new Inner()??3.匿名嵌套类:可视为外部类的局部变量,可访问外

4.22 嵌套类
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!!!");}}}

?

?

?

?

热点排行