内部类引用外部类方法,逻辑有些绕。
1.内部类生成对外部类对象的引用
外部类名称+.this;
2.外部类提供实例化内部类的方法,因为拥有外部类对象之前是不能创建内部类对象的,内部类对象会暗暗地连接到创建她的外部类对象中。
相当抽象的图像说明:
代码:
public class NotThis {
public void fun()
{
System.out.println("function in out class");
}
private class Inner
{
//內部类中生成对外部对象的引用
public NotThis outer()
{
return NotThis.this;
}
}
//外部类中提供实例化内部类的方法
public Inner inner()
{
return new Inner();
}
public static void main(String args[])
{
NotThis dotThis=new NotThis();
NotThis.Inner inner=dotThis.inner();//內部類不能存取。
// NotThis.Inner inner=dotThis.new inner();//可取方法
// NotThis.Inner inner=new NotThis.Inner(); 不可取
inner.outer().fun();
}
}