这是一道拓展题,我在练的时候写的时候写不出来,不知道为啥中间是这么写的:
public class TestAnonymous2 {
public static void main(String[] args) {
Test.function().method();
}
}
interface Inter{
void method();
}
class Test{
public static Inter function(){
return new Inter(){
@Override
public void method() {
System.out.println("测试");
}};
}
}
以下是我的理解:我看main方法里面用类名调用function()方法,说明这个方法是static修饰的,然后后面有接着个method(),那方法是在function()方法的里面,里面的new Inter是为了不让原来Test不用写Implements Inter 而这么写来实现method方法的么?
return new Inter(){
@Override
public void method() {
System.out.println("测试");
}};
我重点解释一下这段代码。
我们知道,接口是不能直接new的,但是在这里却是合理的,原因就是java帮我们创建了匿名类,默认实现了Inter接口。相当于:
class MorenClass implements Inter {
@Override
public void method() {
System.out.println("测试");
}
}
class Test{
public static Inter function(){
return new MorenClass().method();
}
}
这就是逐级调用 重写了method方法 没有坑啊
function()返回的是Inter接口;方法体里是匿名内部类也就是Inter接口的子类;所以可以直接调用父类method()方法。
可以理解为
public class TestAnonymous2 {
public static void main(String[] args) {
Test.function().method();
}
}
interface Inter{
void method();
}
class Test implements Inter{
public static Inter function(){
return new Test();
}
@Override
public void method() {
System.out.println("测试");
}
}