6
interface Shape { }
class Circle implements Shape { }

class ShapeContainer<T extends Shape> {
    T sh;
    public ShapeContainer(T newInstance) {
        sh = newInstance;
    }
    ...
}
class Main {
    public static void main(String[] a) {
        ShapeContainer<Shape> A = new ShapeContainer(new Circle());
        ShapeContainer<? extends Shape> B = new ShapeContainer(new Circle());
    }
}

What are the pros and cons of declaring the variable as ShapeContainer<Shape> A vs ShapeContainer<? extends Shape> B

What condition should each one be preferred?

Bhuvan
  • 4,028
  • 6
  • 42
  • 84
  • 2
    The duplicate anwers talk about the genrics in the method input params. This question is about variable declaration of handling of the output – Bhuvan Nov 15 '22 at 05:02
  • 1
    Since Generics are class invariant, the difference will occur in a method like this: ```public List super E> union(List extends E> l1, List extends E> l2) { Iterator extends E> iterator = l1.iterator(); //will compile fine Iterator iterator = l2.iterator();// wont compile because list l2 is collection of subtypes of E and iterator should also be like that.. ```` For eg if you create two lists with List and List and you want to make union of those two and store in List it should be possible with the function specified above. Hope this helps – user1673567 Nov 16 '22 at 06:50
  • 1
    Gist is if you are expecting subtype of Elements we should use - extends E> – user1673567 Nov 16 '22 at 06:53
  • @user1673567 that make sense for input variable of a method. My question is about output variable declaration – Bhuvan Nov 17 '22 at 06:39
  • If you see the output variable here which I used to depict the difference is - Iterator extends E> iterator and Iterator.. let me know if I am still not clear – user1673567 Nov 17 '22 at 08:11

0 Answers0