0

I am trying to better my understanding Java interfaces and have the following problem with some very basic, code.

The following creates two classes which implement the same interface. I then create two ArrayLists to hold objects of these two classes. I then want to create a single enhanced-for loop which goes through each list and performs the method originally defined in the interface.

I thought that i could use a loop which instead of taking in a specific class type as its parameter could use an Interface type instead, This would then allow me to use any class which implements that interface, but it seems i have made mistake.

How would i go about creating a for loop which allowed only classes which implement an interface to be operated on?

interface Valueing{
    double getValue();
}

class Coin implements Valueing
{
    private double coinVal = 0.0;
    Coin(double initVal){
        coinVal = initVal;
    }
    public double getValue(){
        return this.coinVal;
    }
}

class Note implements Valueing
{
    private int noteVal = 0;
    Note(int initVal){
        noteVal = initVal;
    }
    public double getValue(){
        return (double)noteVal;
    }
}

public class IFaceBasics{
    public static void main(String[] args){
        ArrayList<Coin> myChange = new ArrayList<Coin>();
        myChange.add(new Coin(0.01));
        double totalChange = sumValues(myChange);

        ArrayList<Note> myNotes = new ArrayList<Note>();
        myNotes.add(new Note(5));
        double totalNotes = sumValues(myNotes);
    }

    public double sumValues(ArrayList<Valueing> a){
        double totalSum = 0;
        for(Valueing avg : a) 
        {
            totalSum += avg.getAverage();
        }
        return totalSum;
    }
}

Thanks for any feedback.

Pike Man
  • 355
  • 2
  • 4
  • 13

1 Answers1

5

You've almost got it right, you'd just need to change

public double sumValues(ArrayList<Valueing> a){

to

public double sumValues(ArrayList<? extends Valueing> a){

<? extends Valueing> means "Valueing or any of its sub-types", so this would let the method accept an ArrayList<Coin> or ArrayList<Note> as well as ArrayList<Valueing>.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • 1
    And instead of programming to concrete classes you should be using interfaces. So `List` instead of `ArrayList`, but that is more of a design thing, it should work regardless of that. – M. Deinum Jan 23 '14 at 10:50
  • Thanks, was learning Generics and then skipped to far ahead before i had read http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html. – Pike Man Jan 23 '14 at 11:02