简体   繁体   English

在不同的类中调用相同的函数

[英]Call the same function in different classes

I have a function eventIterable() in six different classes, each with different names. 我在六个不同的类中都有一个函数eventIterable() ,每个类具有不同的名称。 These classes are being stored in an Object[] . 这些类存储在Object[]

I have a custom ArrayList class (I had to create my own - long story, don't bother suggesting I use the standard one), and within it, you can access indexes from the ArrayList . 我有一个自定义的ArrayList类(我不得不创建自己的长篇小说,不要打扰我建议使用标准类),并且在其中,您可以从ArrayList访问索引。

Each of these class objects are stored at an index in the array list. 这些类对象中的每一个都存储在数组列表中的索引处。 However, since the type of the array is Object , I can't call the functions. 但是,由于数组的类型是Object ,所以无法调用函数。 I can't change from Object to a specific class because each of the classes is unique. 我无法从Object更改为特定的类,因为每个类都是唯一的。 They all share the eventIterable() function, however. 它们都共享eventIterable()函数。

The goal is to be able to iterate through all of the classes in the ArrayList , and run the eventIterable() function within each class. 目标是能够遍历ArrayList中的所有类,并在每个类中运行eventIterable()函数。

You should create an interface containing the eventIterable() method, and make all of the classes implement that interface. 您应该创建一个包含eventIterable()方法的接口,并使所有类都实现该接口。

You can then use a list of that interface rather than a list of objects. 然后,您可以使用该接口的列表而不是对象的列表。

Create an interface that represents this behavior (hard to know what it is) that has a single method called eventIterable . 创建一个表示此行为(很难知道它是什么)的接口,该接口具有一个名为eventIterable方法。 Then just change the return type to this interface. 然后只需将返回类型更改为此接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM