简体   繁体   中英

Issue with generics and <E extends …>

I have two classes like this

public class Wire<E extends Electricity> implements Connection<E> {
    private ArrayList<Inlet<E>> outlets = new ArrayList<Inlet<E>>();

    public void outputToAll() {     
        for (Inlet<E> inlet : outlets){
            inlet.addToStore(new Electricity(amountPer));
        }
    }
}

and

public abstract class Inlet<E> {    
    private E store;

    public void addToStore(E inputObj){
       this.store.add(inputObj);
   }
}

Inlet doesn't have any errors, but Wire gives me the error that

The method addToStore(E) in the type Inlet is not applicable for the arguments (Electricity)

However, since in outputToAll E must extend electricity, so Inlet is at least Inlet, why does passing an Electricity object to addToStore not work?

And if the compiler isn't smart enough to know that this will work, what is a good workaround?

You don't need the Wire class to be generic for what it seems like you want to do.

If you just have:

public class Wire implements Connection<Electricity> {
    private ArrayList<Inlet<Electricity>> outlets = new ArrayList<Inlet<Electricity>>();

    public void outputToAll() {     
        for (Inlet<Electricity> inlet : outlets){
            inlet.addToStore(new Electricity(amountPer));
        }
    }
    ...
}

This class will ( likely , as I can't see the rest of it) work for subclasses of Electricity too, due to the Liskov substitution principle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM