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.