I'm trying to build a generic class whose constructor introduces an additional type, but the compiler says no-no.
I don't quite understand why the following doesn't work:
public class Foo<T>
{
public Foo<T,TBar>(TBar tBar)
{
...
}
}
It's not critical as I can write the class using a fluent api (which might be preferred), but I'd still like to understand why I can't. The only explanation I can think of is that the compiler doesn't like method-level generic type declaration mixed with class-level generic type declaration.
Generic constructors Constructors are similar to methods and just like generic methods we can also have generic constructors in Java though the class is non-generic. Since the method does not have return type for generic constructors the type parameter should be placed after the public keyword and before its (class) name.
Since the method does not have return type for generic constructors the type parameter should be placed after the public keyword and before its (class) name. Once you define a generic constructor you can invoke (instantiate the class using that particular constructor) it by passing any type (object) as parameter.
In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype.
Although the Entry class isn't generic, it has a generic constructor, as it has a parameter element of type E. The generic type E is bounded and should implement both Rankable and Serializable interfaces.
It is not possible. The constructor is not called like a method, it is invoked by specifying the class name only (after the new
keyword). Normal methods, on the other hand, can have additional generic type arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With