2014-01-23 27 views
0

我试图更好地理解Java接口,并对一些非常基本的代码有以下问题。在Java中使用增强for循环与接口?

下面创建两个实现相同接口的类。然后我创建两个ArrayLists来保存这两个类的对象。然后我想要创建一个单一的enhanced-for循环,它遍历每个列表并执行最初在界面中定义的方法。

我以为我可以使用一个循环,而不是接受一个特定的类类型,因为它的参数可以使用接口类型来代替,这将允许我使用任何实现该接口的类,但似乎我有犯了错误。

我该如何去创建一个for循环,它只允许实现一个接口操作的类?

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; 
    } 
} 

感谢您的任何反馈。

+0

使用可以使用泛型http://stackoverflow.com/questions/16707340/when-to-use-wildcards-in-java-generics –

+0

你为什么要尝试在'Valueing'上调用'getAverage()'?这个接口没有这样的方法。 –

+0

编译并运行代码并描述它的错误。 –

回答

5

你几乎得到它的权利,你只需要改变

public double sumValues(ArrayList<Valueing> a){ 

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

<? extends Valueing>意味着“Valueing或任何其子类型的”,因此这将让该方法接受ArrayList<Coin>ArrayList<Note>以及ArrayList<Valueing>

+1

而不是编程到具体的类,你应该使用接口。所以'List'而不是'ArrayList',但这更多的是设计的东西,它应该工作,无论如何。 –

+0

+1的明确解释 –

+0

谢谢,正在学习泛型,然后在阅读http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html之前跳过了很远。 –