关于匿名内部类的一个面试题

题目如下:

按照要求,补齐代码
	interface Inter { 
		void show(); 
	}
	class Outer { 
		//补齐代码 
	}
	class OuterDemo {
	    public static void main(String[] args) {
		      Outer.method().show();
		  }
	}
要求在控制台输出”HelloWorld”。

上面就是这道小小的面试题,首先分析main方法中的方法调用语句,Outer.method(),Outer是直接在后面加了个点调用的method()方法,说明method()方法是Outer类中的一个静态方法,所以我们可以先在代码上写下这个method方法。


然后我们继续看后面,调用的接口Inter的show()方法,说明前面的Outer.method()的类型是Inter类型的,也就是接口类型的,要不然也调用不了这个show()方法,所以我们可以确定method()方法应该有一个Inter类型的返回值。


 

interface Inter{
	void show();
}
 
class Outer{
	public static Inter method(){
		return new Inter(){
			public void show(){
				System.out.println("Hello World");
			};
		};
	}
}
 
class OuterDemo{
	public static void main(String[] args){
		Outer.method().show();
	}
}
发布了61 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_33204444/article/details/98358589