Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics limit type

In Java i have the following Class Structure:

class All
+-- class A extends All
+-- class B extends All

class ContainAll
+-- class ContainA extends ContainAll
+-- class ContainB extends ContainAll

In every "contain" class there is a linked list, and a Method

public addElement(All a) {
    list.add(a)
}

The class ContainAll should not be instanced, but the class ContainA and ContainB can.
How do i make clear, with generics, that addElement in class ContainB can only get Objects from type B, so for Example:

public abstract class ContainAll<T extends All> {}

public class ContainB<T extends B> extends ContainAll<All> {
    public addElement(T b) {
        list.add(b);
    }
}

But this example does not work, i tried it. Thanks for reading.

like image 568
BadJoke Avatar asked Aug 01 '26 00:08

BadJoke


1 Answers

Make your ContainAll class abstract (since one of your requirements is to not be able to instantiate it) and make it implement .addElement():

public abstract class ContainAll<T extends All>
{
    private final List<T> list = new LinkedList<T>();

    // ...

    // FINAL! Subclasses cannot override it
    public final void addElement(final T element)
    {
        list.add(element);
    }
}

Then implement ContainA as ContainAll<A> etc. The .addElement() will work "automatically".

like image 139
fge Avatar answered Aug 03 '26 13:08

fge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!