简体   繁体   中英

How do I create a generics class with another generic class?

I'm not very good with generics or erasure types but I have the following classes:

AbstractEventBuffer<BufferedEvent<T>>

and

BufferedEvent<T>

I have concrete implementations of these classes I'm working with, but the AbstractEventBuffer that takes a BufferedEvent will not let me use T how I have it.

I'm trying to keep these very generic to minimize replication of code later on.

Why can I not create my AbstractEventBuffer class like..

public abstract class AbstractEventBuffer<BufferedEvent<T>>

maybe you think about such declaration (I think this is it):

public abstract class AbstractEventBuffer<E extends BufferedEvent<?>>

or:

public abstract class AbstractEventBuffer<T, E extends BufferedEvent<T>>

or

public abstract class AbstractEventBuffer<E extends BufferedEvent<? extends Object>>

or such:

public abstract class AbstractEventBuffer<BufferedEvent> {

?

I assume you heard the crowd:

Make the class concrete.

Once concrete you can make it be a generic class that only accepts Event (of any type) or subclasses of Event as it's type by doing:

public class Buffer<T extends Event<?>> {

Cheers!

You can't instantiate an abstract class.

I haven't done java in a while (moved on to C#) but if I remember clearly something like this is possible:

public abstract class Buffer<T extends Event<I>>

And of course you first need to extend this abstract class buffer because you can't instantiate a abstract class.

It sounds from your question like you may also want to try something like:

public class EventBuffer<T> extends Buffer<Event<T>> {

Your question is a bit confusing, following code is legal and perhaps doing what you want. The event should probably keep its type parameter for itself but if you insist on using it the first example from zacheusz with two type params is the right way. Don't overdo it:)

class BufferedEvent<T>{}

abstract class AbstractEventBuffer<E extends BufferedEvent>{}

class EventBuffer<E extends BufferedEvent> extends AbstractEventBuffer
{
    public static void main (String[] args)
    {
          EventBuffer<BufferedEvent> buffer = new EventBuffer<BufferedEvent>();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM