Java匿名内部类

203 阅读1分钟
  • 在Java中,接口implements内只能包含常量和抽象方法
  • 要使用接口, 就必须让子类实现接口内所有的抽象方法
  • 匿名内部类相当于创建了 抽象类子类的对象 或 实现接口所有方法的类的对象

题目

解答:

interface Inter{
	void show();
}

class Outer{

	//补齐代码
	public static Inter method(){

		// 创建匿名对象
		Inter my_inter = new Inter(){
			public void show(){
				System.out.println("HelloWorld");
			}
		};

		return my_inter;
	}

}

class OuterDemo{
	public static void main(String[] args){
                // 调用了返回对象的方法(method方法返回了, 实现了接口类Inter 的对象)
		Outer.method().show();
	}
}