java学习笔记之内部类

来源:互联网 发布:sm5 算法 编辑:程序博客网 时间:2024/04/29 03:13
内部类:一个类定义在一个类的内部;A类要直接访问B类中的成员时,可以将A类定义到B类中,作为B类的内部类存在


访问规则:内部类可以直接访问外部类中的成员;外部类要访问内部类只能创建内部类的对象 

内部类有所属,生成的class文件名称为Outer$Inner


内部类相当于外部类中的一个成员,那么就可以被成员修饰符修饰,public、static、private

非静态非私有内部类:如果内部类权限是非私有的,就可以在外部其他程序中被访问到,既可以通过创建外部类对象完成

class Outer{     int num = 9;     class Inner{          void show{              System.out.println(num);}      }} class outerInnerTest{        Outer.Inner in = new Outer().new Inner();        in.show;}


访问静态非私有内部类的非静态成员

class Outer{     int num = 9;     static class Inner{          void show{              System.out.println(num);}      }} class outerInnerTest{        Outer.Inner in = new Outer.Inner();//不需要new外部类对象,但是内部类需要持有外部类的引用        in.show;}



访问静态非私有内部类的静态成员

class Outer{     int num = 9;     static class Inner{         static  void show{              System.out.println(num);}      }} class outerInnerTest{        Outer.Inner in = new Outer.Inner();//不需要new外部类对象,但是内部类需要持有外部类的引用        in.show;}


注意:非静态内部类不能定义静态方法,在非静态的内部类中只允许定义静态的常量

一些有意思的地方


class Outer{      int num =2;      class Inner{          int num =3;          void show{                int num =4;                System.out.println(num);//输出局部变量                System.out.println(this.num);//this用于区分局部和成员,省略了Inner,也就是Inner.this.num                              System.out.println(Outer.this.num);//输出Outer类的局部变量}} public void method(){ new Inner().show();}}class OuterInnerTest{ public static void main(String[] args){new Outer().method();}}


//也可以将内部类放到局部的位置上


class Outer{      private int num =4;      public void method{      class Inner{          int x = 7;          void show()               {             //System.out.println(x);             //从内部类中访问局部变量x,x需要被声明为最终类型---final修饰;java中内部类不允许直接访问局部所在的局部变量,原因该局部变量与对象的生命周期不同,当show方法弹栈之后,x也就不再存在。             System.out.println(num);}

非静态内部类中不可以定义静态方法;

内部类可以私有;

静态内部类只能访问外部类中的静态成员;

内部类也可以是抽象的。 

0 0