意义:
1)可以访问外部类的数据,包括私有数据。
2)同一包的其他类看不到。
3)使用一种匿名类可以节约大量代码。
特点:内部类相当于内部类有个实例域引用了外部类。如图:
实例:
public class Out {
boolean choice = true;
public static void main(String[] args){
new Out().methodOut();
}
public void methodOut(){
In in = new In();
in.methodIn();
}
public class In{
public void methodIn(){
if(choice){
System.out.print("Right!");
}
}
}
}
在这里:
In in = new In();//编译器把代表外围类的this关键字作为编译器为In类创建的构造器的参数In in = new In(this);
构造器为:
public In(Out this){
outer = this
}
这就是内部类既可以访问自己的数据域也可以访问外围类的数据域的原因。
一,局部内部类
也就是常见的在方法中创建对象,修改上面部分的代码:
public class Out {
boolean choice = true;
public static void main(String[] args){
new Out().methodOut();
}
public void methodOut(){
class In{
public void methodIn(){
if(choice){
System.out.print("Right!");
}
}
}
In in = new In();
in.methodIn();
}
}
可以看见In对象声明在方法methodOut中。
注意:局部内部类不能用public和private声明,因为他的作用如同他的名字一样,只有methodOut方法可以访问,Out其他方法都不可以,换句话说,她比基本内部类更”内部“。
二,匿名内部类(new后面有没有花括号)
局部内部类的升级版,代码更少,可以补写出类名:
new type(parameters){
method;
}
type是一个类的时候,就是表示这个内部类的老爸,如果是接口就表示它需要实现的借考,method是它要实现的方法,他和局部内部类的区别就在于减少代码。
注意:因为构造方法和类名一致,匿名内部类没有构造器,但是如果有参数需要传递的话,就用到父类的构造方法了,单数如果是实现接口的话,那就只有不能有参数了!
三,静态内部类
当不需要引用其他任何对象,包括外部类时,在类的前面加上static表示静态类,相当于上面图中没有outer引用,类似于静态方法,访问的时候直接使用外部类访问:Out.In in
例如:
public class Out {
public static In methodOut(){
return new In();
}
public static class In{
int i = 1;
}
}
public class StaticInnerClass {
public static void main(String[] args){
Out.In in = Out.methodOut();
System.out.print(in.i);
}
}
总结一句话就是,内部类不需要引用外围类对象。