I am trying to understand "super" and "extends" with respect to Java Generics. For this, I made following example / code:
package com.example.generics;
public class Generics1 {
static <T super Animal> void superDemo() {
}
// "extends" acts like UPPER bound
// in Hierarchy tree up-to that "class"
// we can pass on the objects
static <T extends Dog> void extendsDemoUptoDog(T t) {
System.out.println("received is --> "+t);
}
static <T extends Cat> void extendsDemoUptoCat(T t) {
System.out.println("received is --> "+t);
}
static <T extends Animal> void extendsDemo(T t) {
System.out.println("received is --> "+t);
}
public static void main(String[] args) {
Dog dog = new Dog();
Generics1.extendsDemoUptoDog(dog);
Dog dog1 = new Dog1();
Generics1.extendsDemoUptoDog(dog1);
Dog dog2 = new Dog2();
Generics1.extendsDemoUptoDog(dog2);
Cat cat = new Cat();
Generics1.extendsDemoUptoCat(cat);
Cat1 cat1 = new Cat1();
Generics1.extendsDemoUptoCat(cat1);
Cat2 cat2 = new Cat2();
Generics1.extendsDemoUptoCat(cat2);
Animal animal = new Animal();
Generics1.extendsDemo(animal);
// Doesn't work ... we have violated the UPPER BOUND
// even though "animal" is INHERITED from FatherOfAllAnimal
FatherOfAllAnimal foal = new FatherOfAllAnimal();
//Generics1.extendsDemo(foal);
}
}
class FatherOfAllAnimal{}
class Animal extends FatherOfAllAnimal{}
class Dog extends Animal {}
class Cat extends Animal {}
class Tiger extends Animal {}
class Lion extends Animal {}
class Dog1 extends Dog{}
class Dog2 extends Dog1{}
class Dog3 extends Dog2{}
class Cat1 extends Cat{}
class Cat2 extends Cat1{}
class Cat3 extends Cat2{}
The following is acceptable in method T extends Animal, as in method extendsDemo
.
But why T super Animal is not valid, as in method superDemo
? What is the correct way to express this?