Working on a specific need. Most of online tutorial talks about applying wildcard implementation with Collections. In below example, extends works OK but when I apply super with wildcard bounding getting error. I wish to restrict a method with it super type like said in the below example. Is there any limitation with super that I supposed to know.
class SuperClass3 {
public void display() {
System.out.println("This is display3 method");
}
}
class SuperClass2 extends SuperClass3 {
public void display() {
System.out.println("This is display2 method");
}
}
class SuperClass1 extends SuperClass2 {
public void display() {
System.out.println("This is display1 method");
}
}
Extends works well (with Type bounding NOT with wildcard bounding)...
public <T extends SuperClass2> void displayOutput(T obj) {
obj.display();
}
Try to do the same with Super not working. Throw compile error on method signature.
public <T super SuperClass2> void displayOutputWithSuper(T obj) {
//obj.display();
}
Complete Example ...
package com.tutorial.generic.bounds.wildcard;
import java.util.List;
public class UpperBoundWildcardExample {
class SuperClass3 {
public void display() {
System.out.println("This is display3 method");
}
}
class SuperClass2 extends SuperClass3 {
public void display() {
System.out.println("This is display2 method");
}
}
class SuperClass1 extends SuperClass2 {
public void display() {
System.out.println("This is display1 method");
}
}
public <T extends SuperClass2> void displayOutput(T obj) {
obj.display();
}
public void addData(List<? extends SuperClass2> data) {
}
public <T super SuperClass1> void displayOutputWithSuper(T obj) {
obj.toString();
}
/*
* This wont work
*
* public void addData(<? extends SuperClass2> data){
*
* }
*/
public static void main(String[] args) {
UpperBoundWildcardExample obj = new UpperBoundWildcardExample();
// Oops!!! Error
// obj.displayOutput(obj.new SuperClass3());
// It suppports SuperClass2 & which extends SuperClass2
obj.displayOutput(obj.new SuperClass2());
obj.displayOutput(obj.new SuperClass1());
}
}