10、匿名内部类

内部类

1、在类的内部又定义了一个新的类,被称为内部类。
2、内部类的分类:
静态内部类:类似于静态变量
实例内部类:类似于实例变量
局部内部类:类似以局部变量

匿名内部类

1、匿名内部类是局部内部类的一种,因为这个类没有名字。
2、不适用匿名内部类去调用接口需要,将接口实现,然后new一个类。
3、学习的目的是看得懂其他人的代码,不建议使用。
4、缺点1:太复杂、太乱、可读性差
缺点2:类没有名字,无法重复使用。

public class Test01 {
    
    
    public static void main(String[] args) {
    
    
       
       //不使用内部类去new一个接口的方法是:将接口实现,再new一个实现的类
        MyMath mm = new MyMath();
        mm.mySum(new ComputerImpl(),100,200);

    }
}
//电脑接口
interface Computer{
    
    
    int sum(int a,int b);
}
//接口的实现
class ComputerImpl implements Computer{
    
    
    public int sum (int a,int b){
    
    
        return a+b;
    }
}
//加法的代码
class MyMath{
    
    
    public void mySum(Computer c,int x,int y){
    
    
        int retValue = c.sum(x,y);
        System.out.println(x+ "+" + y +"=" +retValue);
    }
}
        MyMath mm = new MyMath();
        mm.mySum(new Computer(){
    
    
            public int sum(int a,int b){
    
    
                return a+b;
            }
        },100,200);

猜你喜欢

转载自blog.csdn.net/Alopecian/article/details/114522624
今日推荐