class Inner
{
int x = 7;
void funcation()
{
int x =6;
System.out.println(Outer.this.x);
System.out.println(y);
System.out.println("Outer sum="+sum);
}
}
void method()
{
Inner in = new Inner();
in.funcation();
}
}
class Demotext
{
public static void main(String[] args)
{
Outer out = new Outer();
out.method();
}
}
分析:System.out.println(x);有局部变量x时,打印的是内部类里的局部变量x,如果要打印成员变量x=7,则写成System.out.println(this.x);如果要打印外部类的x=5,则写成System.out.println(Outer.this.x);
访问格式:
1、当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中,直接建立内部类对象。格式:外部类名.内部类名 变量名 = 外部类对象.内部类对象
例如以上代码最后两句可写为:Outer.Inner c = new Outer( ).new Inner( );
c.funcation();
2、当内部类在成员位置上,就可以被成员修饰符所修饰。比如,private:将内部类在外部类中进行封装。static:内部类就具备static的特性。当内部类被static修饰后,只能直接访问外部类中的static成员,出现了访问局限。
在外部其他类中,如何直接访问静态内部类的非静态成员呢?
class Without
{
static private int x = 10;
static class Inside //静态内部类
{
void funcation()
{
System.out.println(x);
}
static String a = "hello";
}
}
class DemoText
{
public static void main(String[] args)
{
System.out.println((Without.Inside.a));
new Without.Inside().funcation();
}
}
分析:变量x是静态的,跟着类的加载而直接存在在内存中,可以直接显示,即不用建立外部类对象。而funcation这个方法是非静态的,要调用此方法,就需要新建个内部类对象,再用内部类对象来调用此方法:new Without.Inside().funcation();
在外部其他类中,如何直接访问静态内部类的静态成员呢?
如果funcation这个方法是静态的,访问格式为:Without.Inside().funcation();
注意:当内部类中定义了静态成员,该内部类也必须是static的。当外部类中的静态方法访问内部类时,内部类也必须是static的。
内部类定义在局部时:1、不可以被成员修饰符修饰。2、可以直接访问外部类中的成员,因为还持有外部类中的引用。但是不可以访问它所在的局部中的变量,只能访问被final修饰的局部变量。
例:
class Outside
{
private int x = 6;
void show(final int a)
{
final int y =12;
class Inside
{
void funcation()
{
System.out.println("x="+x);
System.out.println("y="+y);
System.out.println("a="+a);
}
}
new Inside().funcation();
}
}
class DemoText
{
public static void main(String[] args)
{
Outside out = new Outside();
out.show(2);
out.show(3);