内部类:
在类的内部嵌套类,在类的局部或者方法内,叫做内部类。
1 public class Outer { 2 private int a=2; 3 public class Inner{ 4 public void show(){ 5 System.out.println("this is inner"); 6 } 7 } 8 }
调用类:
1 public class Test { 2 public static void main(String ...args){ 3 Outer.Inner in=new Outer().new Inner(); 4 in.show(); 5 } 6 }
输出:
外部类调用内部类的语法:
外部类.内部类 变量 = new 外部类().new 内部类()
内部类可以直接调用外部类的成员。通过this调用(类似隐式调用)
外部类调用内部类的成员需要通过内部类对象调用。
1 public class Outer { 2 private int a=2; 3 public class Inner{ 4 private int a=3; 5 public void show(){ 6 System.out.printf("this is inner %d ",this.a); 7 } 8 } 9 public void show(){ 10 Inner in=new Inner(); 11 System.out.printf("this outer %d ",in.a); 12 } 13 }
1 public class Test { 2 public static void main(String ...args){ 3 Outer.Inner in=new Outer().new Inner(); 4 in.show(); 5 Outer ou=new Outer(); 6 ou.show(); 7 } 8 }
输出:
调用外部类的语法:外部类名.this.变量名字
1 public class Outer { 2 private int a=2; 3 public class Inner{ 4 private int a=3; 5 public void show(){ 6 int a=4; 7 System.out.printf("this is inner %d ",this.a);//内部类的成员 this.变量. 8 System.out.printf("this is inner method %d ",a); 9 System.out.printf("this is outter a %d ",Outer.this.a);//调用外部类的变量语法:类名字.this.变量. 10 } 11 } 12 public void show(){ 13 Inner in=new Inner(); 14 System.out.printf("this outer %d ",in.a); 15 } 16 }
调用类:
1 public class Test { 2 public static void main(String ...args){ 3 Outer.Inner in=new Outer().new Inner(); 4 in.show(); 5 Outer ou=new Outer(); 6 ou.show(); 7 } 8 }
输出: