今天看代码,看到几个概念:内部类、局部类、成员类、静态成员类、匿名内部类;瞬间有种被搞糊涂了感觉。下面是一个小例子来对它们进行说明:
public class ClassTest{ public static void main(String[] args) { ClassTest son = new ClassTest(); //测试匿名类 son.testAnonymous(new AnonymousClass() { @Override public void test() { System.out.println("1 -> " + this.getClass().isMemberClass()); System.out.println("1 -> " + this.getClass().isAnonymousClass()); System.out.println("1 -> " + this.getClass().isLocalClass()); System.out.println("---------------------------------------"); } }); //测试成员类 son.testMember(); //测试静态成员类 new StaticMemberClass(); //测试局部类 class LocalClass{ public LocalClass(){ System.out.println("4 -> " + this.getClass().isMemberClass()); System.out.println("4 -> " + this.getClass().isAnonymousClass()); System.out.println("4 -> " + this.getClass().isLocalClass()); System.out.println("---------------------------------------"); } } new LocalClass(); } private void testAnonymous(AnonymousClass inner) { inner.test(); } private void testMember() { new MemberClass(); } /** * 接口,用于测试内部类 * @author xinghzhang * */ interface AnonymousClass{ public void test(); } /** * 静态成员类 * @author xinghzhang * */ static class StaticMemberClass{ public StaticMemberClass() { System.out.println("3 -> " + this.getClass().isMemberClass()); System.out.println("3 -> " + this.getClass().isAnonymousClass()); System.out.println("3 -> " + this.getClass().isLocalClass()); System.out.println("---------------------------------------"); } } /** * 成员类 * @author xinghzhang * */ class MemberClass{ public MemberClass() { System.out.println("2 -> " + this.getClass().isMemberClass()); System.out.println("2 -> " + this.getClass().isAnonymousClass()); System.out.println("2 -> " + this.getClass().isLocalClass()); System.out.println("---------------------------------------"); } } }
匿名内部类、成员类与局部类
时间: 2024-10-07 14:14:10