zephos2014
zephos2014

Reputation: 331

How to subclass generics properly?

I have searched other questions/answers, an I'm still confused about this JAVA ISSUE.

If I want to subclass a type that takes generic parameters, how would I do so while using generic parameters for the subclass too without it getting shadowed?

For example:

public class A <T> extends ArrayList<T> {}

So if i instantiate my custom class, with say, Integers as the parameter, does it take that value as parameter for <T> for the ArrayList part of it too? If not, then how would I specify the type for the ArrayList?

And I know sub classing containers may not be the best idea in many situations, but in this case I have decided it would be appropriate.

Upvotes: 1

Views: 108

Answers (1)

Assaf
Assaf

Reputation: 1370

yes that would be how one goes about it.

public static void main(String[] args) {
    B<Integer> b = new B<Integer>();
    b.a = 1;
    b.b = "one";

    b.add(1);
    b.add(2);
}

public static class A<T> extends ArrayList<T> {
    public T a;
}

public static class B<T> extends A<T> {
    public T b;
}

if you like you could even have them have different types, as long as you supply the super-class with it's type as well:

public static void main(String[] args) {
    B<Integer, String> b = new B<Integer, String>();
    b.a = 1;
    b.b = "one";

    b.add(1);
    b.add(2);
}

public static class A<T> extends ArrayList<T> {
    public T a;
}

public static class B<U, T> extends A<U> {
    public T b;
}

Upvotes: 1

Related Questions