interface Inter6
{
void show1();
void show2();
}
class Outer6
{//非匿名内部类
// class Inner implements Inter
// {
// public void show1() {
//
// }
// public void show2() {
//
// }
// }
public void method() {
// Inner in = new Inner();
// in.show1();
// in.show2();
//匿名内部类 但是如果我想多次调用 比如两次调用里面的show1和show2
//两次调用new两次太麻烦了 所以可以 Inter6 in = new Inter6()
new Inter6() {
public void show2() {
}
public void show1() {
}
};
in.show1();
in.show2();
}
}
/*
通常的使用场景之一:
当函数参数是接口类型时,而且接口中的方法不超过三个。
可以用匿名内部类作为实际参数作为传递,
*/
//原先的操作:
/*public class InnerClassDemo5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
show(new InterImpl6());
}
//使用接口
public static void show(Inter6 in) {
in.show1();
in.show2();
}
}
//实现接口
class InterImpl6 implements Inter6
{
public void show1(){}
public void show2(){}
}*/
//现在的操作:
public class InnerClassDemo5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
show(new Inter6(){
public void show1(){}
public void show2(){}
});//直接new然后在里面覆盖
}
//使用接口
public static void show(Inter6 in) {
in.show1();
in.show2();
}
}
匿名内部类----应用
最新推荐文章于 2023-12-11 09:32:40 发布