在ArrayList中使用接口 [英] Using an Interface in an ArrayList

查看:124
本文介绍了在ArrayList中使用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个Interface和2个实现它的类.唯一的问题是,这两个类都在其中包含未在接口中列出的方法.我有一个使用接口类型的ArrayList的测试类:

Okay so I have an Interface and 2 classes that implement it. The only problem is both classes have methods within them that aren't listed in the interface. I have a test class that uses an ArrayList of the interface type:

ArrayList<Company> employees = new ArrayList<Company>();

该程序旨在允许创建两个不同类别的员工

The program is designed to allow creation of two seperate classes of employees

public class Salaried implements Company 

public class Hourly implements Company

并允许某些方法与它们一起使用.这两个类既实现接口,又具有自身唯一的其他方法.

and allow certain methods to be used with them. The two classes both implement the interface, but also have additional methods unique to themselves.

在测试类中,我试图使用arrayList存储创建的不同员工,以便稍后使用它们的方法.但是,由于我使用创建雇员时界面中没有的方法,因此该程序将无法编译,也不会让我使用这些方法.

In the test class, I'm trying to use the arrayList to store the different employees that are created, so that their methods can be used later. However the program won't compile as I use methods that aren't in the interface when creating the employees and it won't let me use those methods.

我应该如何解决这个问题?是在接口内还是在类本身内是错误的?

How should I go about fixing this? Is it a mistake within the interface or within the classes themselves?

推荐答案

如果我理解正确,则应该进行转换.尝试使用类型类型转换来调用特定于实现的方法.

If I understand correctly, you should cast. Try type type casting to call implementation specific methods.

ArrayList<Company> companies = new ArrayList<>();

    for (Company c : companies) {
        if (c instanceof Salaried) {
            Salaried s = (Salaried) c;
            //call salaried methods
        } else if (c instanceof Hourly) {
            Hourly h = (Hourly) c;
            //call hourly methods
        } else {
            throw new AssertionError("Unknown subtype of Company found.");
        }
    }

这篇关于在ArrayList中使用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆