局部内部类是最小的结构,在一个方法中进行有一个类,在方法中的类只能在本方法中进行使用,这种形式可以用于包装不期望别人使用里面的方法:
public class LocalInner{
public void saySomething(){
class Inner{
public void saySomethingInner(){
System.out.println("this is inner flag ");
}
}
new Inner().saySomethingInner();
}
}
上面是结果
外部的类不能使用局部类的类,(可以想象怎么才能用到啊,根本没有办法调用)内部类可以使用外部类的参数和内容,是全局变量;
public class LocalInner{
public String local = "outter";
private String localOutter = "localOutter";
public void saySomething(){
class Inner{
String inner = "inner ";
public void saySomethingInner(){
System.out.println("this is inner flag " + localOutter + " local mun : " );
System.out.println("this is inner :" + local);
}
}
new Inner().saySomethingInner();
}
但是局部变量呢:
public class LocalInner{
public String local = "outter";
private String localOutter = "localOutter";
public void saySomething(){
int a = 1;
class Inner{
String inner = "inner ";
public void saySomethingInner(){
System.out.println("this is inner flag " + localOutter + " local mun : " + a );
System.out.println("this is inner :" + local);
}
}
new Inner().saySomethingInner();
}
}
这种方式会抛出一个异常:
所以,局部类要调用局部变量,必须是要final修饰的,不然是不能进行调用的