1 package com.czp; 2 3 /** 4 * 5 * java内部类 6 * @author CaoZP 7 * 8 */ 9 public class OuterClass { 10 11 /** 12 * 13 * 实例内部类 14 * 15 */ 16 public class PublicInnerClass{ 17 18 void test() 19 { 20 System.out.println(getClass()); 21 } 22 } 23 24 /** 25 * 静态内部类 26 */ 27 28 public static class StaticInnerClass{ 29 30 void testX() 31 { 32 System.out.println(getClass()); 33 } 34 } 35 /** 36 * 匿名内部类 37 */ 38 public TestInterface test = new TestInterface() { 39 40 @Override 41 public void print(String str) { 42 System.out.println(str); 43 } 44 }; 45 46 public static void main(String[] args) { 47 OuterClass outerClass = new OuterClass(); 48 //PublicInnerClass的实例化依赖于外部类的实例 49 PublicInnerClass publicInnerClass = outerClass.new PublicInnerClass(); 50 publicInnerClass.test(); 51 //静态内部类的实例化不需要外部类的实例 52 StaticInnerClass staticInnerClass = new StaticInnerClass(); 53 staticInnerClass.testX(); 54 //匿名内部类通常作为一个外部类的成员,通过外围类的实例引用 55 outerClass.test.print("Test"); 56 } 57 } 58 59 interface TestInterface{ 60 61 void print(String str); 62 }