Abbey S
Abbey S

Reputation: 111

Using an Interface in an 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 

and

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.

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?

Upvotes: 0

Views: 8005

Answers (2)

Pravin Sonawane
Pravin Sonawane

Reputation: 1833

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.");
        }
    }

Upvotes: 1

Tigin
Tigin

Reputation: 119

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.

I'm not sure what you mean by this. If you instantiate a variable of type Salaried, you can call your methods specific to the Salaried class. This is also true for Hourly. From there, you can add to your ArrayList since both Salaried and Hourly implements Company.

Upvotes: 0

Related Questions