java 匿名接口_java使用匿名类直接new接口

翻看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 elements() {

return new Enumeration() {

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查看下,

9bd6b4cd3f5e24baf54342fd6e26fcad.png

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

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

a486bbc58527339903c9b435d5bb2c59.png

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

总结:

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

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

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

接口实现方法;

});

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值