版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z249486888/article/details/83246948
匿名内部类,相当于简化的内部类
前提条件:有一个类(具体类或者抽象类)或者接口。
格式: new 类名或者接口名() {重写方法;}
这里new出来的对象相当于类的子类对象或者接口的实现类对象。
实质:创建的是继承了类或实现了接口的子类匿名对象。
/*
匿名内部类面试题:
按照要求,补齐代码
interface Inter { void show(); }
class Outer { //补齐代码 }
class OuterDemo {
public static void main(String[] args) {
Outer.method().show();
}
}
要求在控制台输出”HelloWorld”
*/
interface Inter {
void show();
//public abstract
}
class Outer {
//补齐代码
public static Inter method() {
//子类对象 -- 子类匿名对象
return new Inter() {
public void show() {
System.out.println("HelloWorld");
}
};
}
}
class OuterDemo {
public static void main(String[] args) {
Outer.method().show();
}
}
分析:1、通过main方法中直接调用Outer.method().show()可以分析出method是一个静态方法
2、Outer.method().show()是一个链式编程,Outer.method()是一个对象,即method()返回值为引用类型。
3、通过后面调用show()方法可以分析出method()引用的是一个Inter接口类型。