内部类大致分为4种:
1)匿名内部类(几乎是最常用的)
package com.medivh.learn12; import java.util.Date; /* * 匿名内部类 * 要想实现匿名内部类,那么这个内部类必须是继承了某个类或者实现了某个接口 */ public class AnoInnerClass { public static void main(String[] args) { AnoInner an = new AnoInner(); String time = an.getDate(new Date() { private static final long serialVersionUID = 1L; public String toLocaleString() { return "hell Medivh"; } } ); System.out.println(time); } } class AnoInner { @SuppressWarnings("deprecation") public String getDate(Date date) { return date.toLocaleString(); } }
程序结果:
hell Medivh
package com.medivh.learn12; /* * 静态内部类 */ public class InnerClassTest { public static void main(String[] args) { InnerClass.InnerClass1 i1 = new InnerClass.InnerClass1(); i1.printA(); } public static class Inner { } } class InnerClass { public static int a =4; public static class InnerClass1 { public void printA() { System.out.println(a); } } }
程序结果:
4
package com.medivh.learn12; public class MemInnerClass { public static void main(String[] args) { Test.MemInner mem = new Test().new MemInner(); mem.print(); } } /* * 成员内部类 */ class Test { private int a = 4; public class MemInner { private int a = 5; public void print() { System.out.println("Test.a="+Test.this.a); System.out.println("MemInner.a="+this.a); } } }
程序结果:
Test.a=4
MemInner.a=5
package com.medivh.learn12; public class LocalInnerClassTest { public static void main(String[] args) { LocalInner l = new LocalInner(); l.print(); } } /* * 方法内部类 */ class LocalInner { public void print() { final int a = 4; class Inner { void print() { System.out.println(a);//只能调用final成员变量 } } new Inner().print(); } }
程序结果:
4