Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested generic in a generic class

Tags:

java

generics

I want to provide something like this in my api:

class Foobar extends AbstractThing<Double>

class EventThing<Foobar> {    
            public Foobar getSource();
            public Double getValue();
}

So I write this:

class EventThing<T extends AbstractThing<U>> {    
        public T getSource();
        public U getValue();
}

But java can not resolve the U.

With EventThing<T extends AbstractThing<U>,U> instead it works, but the second U is actually redundant 'cause the AbtractThing define the Type already. So I love to get rid of it.

like image 524
Marcel Jaeschke Avatar asked Dec 15 '10 16:12

Marcel Jaeschke


People also ask

Can I use polymorphism in generics?

The polymorphism applies only to the 'base' type (type of the collection class) and NOT to the generics type.

Can you have generic constructors in Java Though the class is generic?

Constructors are similar to methods and just like generic methods we can also have generic constructors in Java though the class is non-generic.

Can you have a generic method in a non-generic class?

Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.

What is generics polymorphism?

Polymorphism is a property of classes, in that they implement a common interface, or are derived from a base class, implementing virtual methods in a different way to reflect the different behavior of derived classes.


1 Answers

You can't get rid of it. The second U is not redundant. You want the compiler to interpret the first U as a type parameter, but it doesn't. You could also have written this:

class EventThing<T extends AbstractThing<Double>>

Note that Double in this case is a concrete class, and not a type parameter. Compare this to the following:

class EventThing<T extends AbstractThing<U>>

Note that this has the exact same form as the first line of code above. How is the compiler supposed to know that in the first case, Double is meant as a concrete class, while in the second case, U is meant as a type parameter?

The compiler can't know that, and treats the U as a concrete class, just like the Double in the first line. The only way to let the compiler know that U is a type parameter is to specify it as such:

class EventThing<T extends AbstractThing<U>, U>
like image 76
Jesper Avatar answered Nov 06 '22 17:11

Jesper