1 package com.javatest20170224.InnerClass;
2
3 //定义一个外部类
4 class Outter{
5 String name = "outtername";
6 public void test(){
7 System.out.println(this.new Inner().age);
8 }
9 //定义一个内部类
10 class Inner {
11 String name = "Innername";
12 int age= 17;
13 void inner(){
14 String name = "localname";
15
16 System.out.println("inner 方法");
17
18 System.out.println(name);
19 System.out.println(this.name);
20 System.out.println(Outter.this.name);//内部类方法调用外部成员变量。
21 }
22 }
23 }
24 public class InerClassDemo {
25 public static void main(String[] args) {
26 Outter outter = new Outter();
27 System.out.println(outter);//com.javatest20170224.InnerClass.Outter@15db9742
28 Outter.Inner in = outter.new Inner();
29 System.out.println(in);//com.javatest20170224.InnerClass.Outter$Inner@15db9742
30
31 in.inner();//inner 方法
32 outter.test();//17
33
34 }
35 }
静态内部类使用
1 package com.javatest20170224.InnerClass;
2 class Outter2{
3 String name ="outterName";
4 static String name2 = "outtername2";
5 public void test(){
6 System.out.println("Outtertest");
7 }
8 static class Inner{
9 String name = "InnnerName";
10 static int age =19;
11 void innerTest(){
12 String name = "InnerTestname";
13 System.out.println(name);
14 System.out.println(this.name);
15 //静态内部类可以直接访问外部静态成员。
16 System.out.println(name2);
17 //静态内部类通过外部类对象访问外部非静态成员。
18 System.out.println(new Outter2().name);
19 new Outter2().test();
20 }
21 }
22 }
23 public class StaticInnerClass {
24 public static void main(String[] args) {
25 Outter2 outter2 = new Outter2();
26 Outter2.Inner in =new Outter2.Inner();
27 in.innerTest();
28 //测试类可以直接通过完整的类名调用静态内部类的静态成员,
29 System.out.println(Outter2.Inner.age);//19
30 }
31 }