class beyond{
publicstaticvoidmain(String []args){
//外部类名.内部类名 对象名 = 外部类名.内部类对象(new 内部类名)/*Outer.Inner yy = Outer.new Inner(); 类里面有个非静态方法,需要new创建Inner对象;
正常的形式是这样的,但是我们习惯将new放在前面即以下形式*/
Outer.Inner yy = new Outer.Inner();
yy.method();
Outer.Inner2.print();//一路 类名.调用 即可;
}
}
class Outer{
static class Inner{
publicvoidmethod(){
System.out.println("method");
}
}
static class Inner2{
publicstaticvoidprint(){
System.out.println("print");
}
}
}
例题:
要求:用已知的变量,在控制台输出30,20,10.
class Test1_InnerClass{
publicstaticvoidmain(String [] args){
Outer.Inner yy = new Outer().new Inner();
yy.show();
}
}
//内部类之所以能获取到外部类的成员,是因为它能获取到外部类的引用外部类名.this;
class Outer{
publicint num = 10;
class Inner{
publicint num = 20;
publicvoidshow(){
int num = 30;
System.out.println(num);//局部变量num=30;
System.out.println(this.num);//成员变量num=20;
System.out.println(Outer.this.num);//外部类的成员num=10;
}
}
}