java使用匿名类直接new接口

本文解析了Vector类中的elements()方法,该方法返回一个枚举Enumeration,用于遍历Vector的所有元素。文章探讨了此方法的实现机制,并通过示例展示了如何利用内部类实现接口的方式简化代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

翻看Vector代码的时候,看到这么一段。

/**
     * Returns an enumeration of the components of this vector. The
     * returned {@code Enumeration} object will generate all items in
     * this vector. The first item generated is the item at index {@code 0},
     * then the item at index {@code 1}, and so on.
     *
     * @return  an enumeration of the components of this vector
     * @see     Iterator
     */
    public Enumeration<E> elements() {
        return new Enumeration<E>() {
            int count = 0;


            public boolean hasMoreElements() {
                return count < elementCount;
            }


            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

 

 Enumeration是个接口,内部定义此处不缀述。

此处用到了这种new接口的使用方法,如果有些场合,只需要临时需要创建一个接口的实现类,上面的"技巧"可以用来简化代码.
在结合接口内部的方法设定,即可实现强大的处理方式,而省去很多单独处理逻辑问题。

我们在仔细看,会发现实现的接口实例中并没有elementCount,而elementCount是在Vector中定义的,那么如果调用该方法,返回一个接口实例,在使用该接口实例的时候,如何获取到该值?
于是写一个demo查看下,

会发现返回的实例里面维护了一个包含v实例成员变量的实例指向。所以在其方法实现里面可以使用到该值。(至于其如何实现的为探究,读到此文知道的读者可以留言,谢谢)

那么会想,是否返回一个对象都会封装一个此类指向呢,可以自己按照此种方式写一个试试。

Car是一个接口,按照上述方式模式实现的,存在上述所说引用;Student并没有。

总结:

1、适当的时候巧用返回接口实例方式,可结合模式方式实现某种功能简化;

2、是否可以利用其引用处理某些问题,什么样的修饰符的成员变量能被引用对象实现,这种设计的初衷考虑哪些等等,值得神经的时候思考下。

3、另外new 接口方式可以当做参数传递。如t.inject(new Car(){

  接口实现方法;

});

 

转载于:https://www.cnblogs.com/X-World/p/5688224.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值