首页
学习
活动
专区
工具
TVP
发布

面向对象的编程-Application 14

Previously on OOP:

In order to implement Iterator, a class must implement(s) Iterable interface and over ridding the three abstract methods in this interface:hasNext(), next() and iterator(). The previous two are simple, however, the last one is rather difficult, since it requires to return anIteratorobject. We have made our decision to create a new nested class to extend(s)Iteratorinterface.

Solution 1: staticclass

这种nested class和regular classes非常相似,只是被定义在其他类的.java文件中。

为了体现RSIterator类是一个nested class,这个类的声明所使用的关键字是:private static class。

又因为RSIterator类implementsIteratorinterface,所以需要重载Iterator类中所有的abstract methods,即hasNext()andnext()。由此可见,Iteratorinterface中的abstract methods比Iterable interface少一个iterator()函数。

然后,我们可以发现,RSIterator类和RandomSequence类的attributes + overridinghasNext()andnext()methods部分非常相似的,有区别的主要是constructor部分。RSIterator类的constructor传入的参数是RandomSequence类型的,并且把RandomSequence类中存放随机数的数组赋值给attributessequence数组。

以上是RSIterator类的代码,因为RSIterator类是Iteratorinterface的子类,所以在RandomSequence类的iterator()函数中,可以返回RSIterator类的实例。

Solution2:inner class

Inner class和static class的区别就在于它能access its outer class with a reference。

在类的声明方面,inner class比static class少了一个关键字:static。

在代码编写方面,区别也是在RSIterator类的constructor,因为inner class能直接访问outer class(即RandomSequence类)的attributes and methods。

Solution3:anonymousclass

这种nested class要定义在某一个函数里面,并且没有class的声明行和名称,这也就是被称之为“匿名”的原因。因为这个anonymous class存在的意义和目的在于解决RandomSequence类中的iterator()函数重载的问题,所以它的定义就放在这个函数中即可。

在“return new Iterator()”后面的一组花括号中,是anonymous class的定义。同时,RandomSequence类的iterator()函数的返回值是一个Iterator类型的实例,由此可见,“return new Iterator()”还顺便创建了一个anonymous class的实例。

相比之下,如果只是调用Iterator interface的constructor来创建实例,“return new Iterator()”后面不应该是花括号,而是分号。

总之,使用nested class来解决iterator()函数的重载问题确实比较绕。好在本课程的考试中是不需要使用Iterator的,因为遍历一个数组用for statement or for each statement都可以实现。所以在这个例子中,我们需要掌握的是:

(1)能依葫芦画瓢地运用Iterator。尤其是outer class使用Iterable interface,inner class使用Iterator interface。

(2)a sequence of random numbers是怎么创建的。

欢迎使用本黄鸭编写的小程序~

微信公众号二维码:

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20181012G1HFV600?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券