内部类
内部类即为定义在类内部的类.
内部类有两种:1.定义在类的成员位置,叫做成员内部类;2.定义在类的局部位置上,叫做局部内部类.
成员内部类的使用:
1.使用public修饰成员内部类
1 class Outer{ 2 int num = 10; 3 4 class Inner{ 5 void show(){ 6 System.out.println(num); 7 } 8 } 9 } 10 11 public class InnerClassDemo1 { 12 13 public static void main(String[] args) { 14 //调用成员内部类中的show函数 15 Outer o = new Outer(); 16 17 Outer.Inner in = o.new Inner(); 18 19 Outer.Inner in1 = new Outer().new Inner(); 20 21 in.show(); 22 23 in1.show(); 24 25 } 26 27 }
使用外部类的对象进行内部类对象的创建 Outer.Inner in = new Outer().new Inner();
2.使用static修饰成员内部类,并调用在这个成员内部类中的静态方法
1 class Outer1{ 2 int num = 10; 3 4 static class Inner{ 5 int num2 =100; 6 7 public void show(){ 8 System.out.println(num2); 9 } 10 public static void A(){ 11 System.out.println("我是静态中的num2"); 12 } 13 } 14 } 15 16 public class InnerClassDemo2 { 17 18 public static void main(String[] args) { 19 Outer1.Inner in = new Outer1.Inner(); 20 in.show(); 21 Outer1.Inner.A(); 22 } 23 24 }
因为这个成员内部类是使用static进行修饰的,因此可以直接使用内部类的类名来进行创建就可以了----内部类的名字就是Outer.Inner
Outer.Inner in = new Outer.Inner();
3.使用private修饰成员内部类
1 class Outer2{ 2 private int num = 100; 3 4 5 public void method(){ 6 Outer2.Inner in = new Outer2.Inner(); 7 System.out.println("我是num" + num); 8 in.show(); 9 } 10 private class Inner{ 11 int num1 = 200; 12 public void show(){ 13 System.out.println("我是num1" + num1); 14 } 15 } 16 } 17 18 public class InnerClassDemo3 { 19 20 public static void main(String[] args) { 21 Outer2 o = new Outer2(); 22 o.method(); 23 } 24 25 }
因为是private修饰了,只能在外部类的一个方法创建它的对象,并调用.
Outer.Inner in = new Outer.Inner();
局部内部类:
需要注意的就是,在使用外部类成员函数的局部变量的时候,变量要加上final才可以正常使用.如下面程序中的num2,一定要使用final2进行修饰.
1 class Outer3{ 2 3 int num1 = 3; 5 void show(){ 6 final int num2 = 5; //这个很重要,一定要记得加上final 8 class Inner{ 9 int num3 = 7 ; 10 void method(){ 11 System.out.println("num3======" + this.num3); 12 System.out.println("num2======" + num2); 13 System.out.println("num1======" + Outer3.this.num1); 14 } 15 } 16 Inner in = new Inner(); 17 in.method(); 18 } 22 } 23 24 public class InnerClassDemo4 { 25 26 public static void main(String[] args) { 27 // 28 Outer3 o3 = new Outer3(); 29 o3.show(); 30 } 31 32 }
最后,匿名内部类.
使用它主要是方便,例如在后面的文件过滤器中,使用匿名内部类是很方便的.
记住格式:
(new 父类或父接口名(){
实现对抽象函数的复写;
例如show函数.
});
那么之后调用show函数就可以直接.show()函数调用:
(new 父类或父接口名(){
实现对抽象函数的复写;
例如show函数.
}).show();