0

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?

multitaskPro
  • 569
  • 4
  • 14
  • 5
    Well it can't always work. You are saying `inlet` is an `Inlet` with `E extends Electricity`. But you are trying to give it an `Electricity`, when `E` could be different (a subclass of `Electricity`). – Tunaki Apr 23 '16 at 21:18
  • Possible duplicate of [Is List a subclass of List? Why aren't Java's generics implicitly polymorphic?](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p) – lkq Apr 23 '16 at 21:59

1 Answers1

2

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.

Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93