静态内部类,局部内部类和匿名内部类

//局部内部类和其他类一同被编译,但是局部内部类有自己的作用域,超出那个范围即无效
//第一种情况:在函数内
public class InnerClass {
public A a(){
		class AA implements A{
			int a=3;
			@Override
			public int value() {
				System.out.print(a*4);
				return 3*a;
			}
			}
		return new AA();
		
	}
}
public class Test {

	/**
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
     InnerClass innerClass=new InnerClass();
     A aa=innerClass.a();
     aa.value();
	}

}
public interface A {
     int   value();
}
//第二种情况:在代码块内
public class InnerClass {
public void a(boolean b) {
		if (b) {
			class AA implements A {
				int a = 3;
				@Override
				public int value() {
					System.out.print(a * 4);
					return 3 * a;
				}
			}
			A hiA=new AA();
			hiA.value();
		}
}
public class Test {

	/**
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
     InnerClass innerClass=new InnerClass();
     innerClass.a(true);
	}

}
public interface A {
     int   value();
}
	}
//匿名内部类
public class InnerClass {
public A a() {
			return new AA(){
				private int i=9;
				public int value() {
					System.out.println(i);
					return i;
				}
			};
		}
public class Test {

	/**
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
     InnerClass innerClass=new InnerClass();
     A dAa= innerClass.a();
     dAa.value();
	}

}
public interface A {
     int   value();
}
public class AA implements A {

	@Override
	public int value() {
		// TODO Auto-generated method stub
		return 0;
	}

}

}

你可能感兴趣的:(匿名内部类)