JAVA匿名内部类

1.什么是匿名内部类

即一个类中包含一个没有名字的类

2.匿名内部类的使用
public interface People {
    public void doThings();
}

public class Children {
    public People getPeople()
    {
        return new People() { //匿名内部类

            @Override
            public void doThings() {
                System.out.println("吃东西");
            }
        };
    }
    public static void main(String[] args) {
        Children c =new Children();
        c.getPeople().doThings();
    }
}

// 接口的普通实现
public class Womens implements People{ 

    @Override
    public void doThings() {
        System.out.println("吃东西");
    }
    public static void main(String[] args) {
        Womens wo = new Womens();
        wo.doThings();
    }
}

匿名内部类一般使用 (new 接口或抽象类 )实现,上述代码中Children类中的return new People()就是构造了一个匿名内部类,就相当于构造了一个Womens类实现了People接口,只是没有具体的名字。

这里要说的是一种特殊情况,就是将普通类当成基类来使用,当你new 一个普通类时,eclipse编辑器并不会提示你这样写。

// 普通类
public class Man {
    private int money;

    public Man(int money){
        this.money = money;
    }
    public int value()
    {
        return money;
    }
}

public class Women {

    public Man getMan(int x)
    {
        // 构造了一个以普通类为基类的匿名内部类
        return new Man(x) {
            public int value()
            {
                return super.value()*47;
            }
        };
    }


    class Child extends Man
    {
        public Child(int money) {
            super(money);
        }
        public int value(){
            return super.value()*47;
        }

    }
    public static void main(String[] args) {
        Women women = new Women ();
        Child chid =  women.new Child(9);
        System.out.println(chid.value());
    }
}

定义了一个Man的普通类,Women类中的getMan()方法返回构造了一个匿名内部类,就相当于写了一Child类继承了Man类,覆盖了value()方法。只是没有名字罢了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值