<? super Animal> means animal or it's superclass only. Then why inside the method it's allowing to add Dog object even though it's a subclass of Animal? This program compiles and runs!
import java.util.*;
class Cat {}
class Animal{Animal() {System.out.println("Animal constructor");}}
class Dog extends Animal{Dog() {System.out.println("Dog constructor");}}
public class GenericDemo5 extends Animal{
public static void main(String r[]) {
List l1 = new ArrayList(); //can add anything since no type here
l1.add(new Dog());
l1.add(new Animal());
l1.add(30);
met(l1);
System.out.println(l1); }
public static void met(List<? super Animal> l2) {
l2.add(new Animal());
l2.add(new Dog());
System.out.println(l2); }}
Even with Generic Instantiation(shown below) same output!! This also compiles and runs!
import java.util.*;
class Cat {}
class Animal{Animal() {System.out.println("Animal constructor");}}
class Dog extends Animal{Dog() {System.out.println("Dog constructor");}}
public class GenericDemo11 extends Animal{
public static void main(String r[]) {
List<Animal> l1 = new ArrayList<Animal>(); //can add anything
l1.add(new Dog());
l1.add(new Animal());
met(l1);
System.out.println(l1); }
public static void met(List<? super Animal> l2) {
l2.add(new Animal());
l2.add(new Dog());
System.out.println(l2); }}
And it gets more peculiar! If I change it to Dog during instantiation and inside Wild Card, it says you can't add Animal object from within method, which according to me it should. <? super Dog> means Dog and it's superclass.
import java.util.*;
class Cat {}
class Animal{Animal() {System.out.println("Animal constructor");}}
class Dog extends Animal{Dog() {System.out.println("Dog constructor");}}
public class GenericDemo11 extends Animal{
public static void main(String r[]) {
List<Dog> l1 = new ArrayList<Dog>(); //can add anything
l1.add(new Dog());
met(l1);
System.out.println(l1); }
public static void met(List<? super Dog> l2) {
l2.add(new Animal()); //ERROR!
l2.add(new Dog());
System.out.println(l2); }}
Help please! Thank you.