时间:2022-08-08 08:20:09 | 栏目:JAVA代码 | 点击:次
class Outer
{
int x = 3;
class Inner{
void function(){
System.out.println("inner : " + x);
}
}
void method(){
Inner in = new Inner();
in.function();
}
}
class InnerClassDome
{
public static void main (String[] args)
{
Outer out = new Outer();
out.method();
}
}
class Outer
{
int x = 3;
class Inner{
void function(){
System.out.println("inner : " + x);
}
}
void method(){
Inner in = new Inner();
in.function();
}
}
class InnerClassDome
{
public static void main (String[] args)
{
//Outer out = new Outer();
//out.method();
Outer.Inner in = new Outer().new Inner();
in.function();
}
}
之所以可以直接访问外部类的成员,是因为内部类中持有了一个外部类的引用,格式: 外部类名.this
class Outer
{
int x = 3;
class Inner{
int x = 4;
void function(){
int x = 6;
System.out.println("inner : " + x);
System.out.println("inner : " + this.x);
System.out.println("inner : " + Outer.this.x);
}
}
void method(){
Inner in = new Inner();
in.function();
}
}
class InnerClassDome
{
public static void main (String[] args)
{
//Outer out = new Outer();
//out.method();
Outer.Inner in = new Outer().new Inner();
in.function();
}
}