Inheritance of Wildcards

Java-Inheritance of Wildcards

Inheritance of Wildcards

If we have two different wildcard instantiations of a type or related types, how, if at all, are they related? For example, can an unbounded wildcard be assigned a value with a more restrictive bound because it can hold any instantiation? The answer is yes. For example:

Inheritance of Wildcards

For purposes of assignability, wildcard instantiations can be considered as types with possible supertype or subtype relationships determined by their bounds. Unbounded wildcard<?> is really just a wildcard with a upper bound of the type parameter of that class or Object. Because, the default upper bound of the type parameter is Object. So we can read the object as the Object type:

Inheritance of Wildcards

The rule is that if the “base” generic, raw type is assignable and the bounds of the wildcard instantiation are also assignable, the overall types are assignable. Let’s look at another example:

Inheritance of Wildcards

The second statement says is that some GenSub of Data3 types can be treated as some GenSuper of Data1 types through the wildcard instantiation. There is no conflict here. GenSub is a subclass of GenSuper. And we can read the elements from Data3 to Data1.

Program

Inheritance of Wildcards


Program Source

class GenSuper<T> {

    private T t1;

    GenSuper(T t) {
        t1 = t;
    }

    void setT1(T t) {
        t1 = t;
    }

    T getT1() {
        return t1;
    }
}

class GenSub<T> extends GenSuper<T>{

    private T t2;

    GenSub(T t1,T t) {
        super(t1);
        t2 = t;
    }

    void setT2(T t) {
        t2 = t;
    }

    T getT2() {
        return t2;
    }
}

class Data1 {
}

class Data2 extends Data1 {
}

class Data3 extends Data2 {
}

class Data4 extends Data3 {
}

public class Javaapp {

    public static void main(String[] args) {
        
        GenSub<? extends Data3> d3gen = new GenSub<Data4>(new Data4(),new Data4());
        
        GenSuper<? extends Data1> d1gen = d3gen;
        Data1 d1 = d1gen.getT1();
        System.out.println("d1-> "+d1.getClass().getName());
    }
}

Leave a Comment